I am making a game using cocos2d and SpriteBuilder. There is a hero sprite and coins, that should be collected by him. That's a horizontal scrolling game, so every time hero touches a coin, this coin changes it's x-coordinate 2000px to the right and new y-coordinate is generated at random. Using update method I move it to the visible area as a "new" coin. But when hero flyies by and doesn't collect it ,coin must change coordinates only when it's already off the screen, so I tried this solution:
-(void)update:(CCTime)delta{
_coin.position=ccp(_coin.position.x - delta * scrollSpeed, _coinY);
if (CGRectIntersectsRect(_hero.boundingBox,_coin.boundingBox)) {
_coinY=arc4random() % 801 + 100;
_coin.position=ccp(_coin.position.x + 2000.f,_coinY);
}
else if(_hero.position.x >= _coin.position.x + 150){
_coinY=arc4random() % 801 + 100;
_coin.position=ccp(_coin.position.x + 2000.f,_coinY);
}
It works,but after that I found a small bug(I am not sure, whether it's related to this code) : sometimes, when hero touches coin, hero is like pushed away to the left. I have no idea why.
How to fix it?
Is that way, that I am using for coin ,right?
I see 2 issues with your approach:
1. Hero bounces of the coin.
To fix this you need to make your coin a sensor. This way you will still be notified about collisions, but the hero will simply pass through the coin without actually hitting it.
I'm not sure if you can set this in SpriteBuilder, but probably you can enumerate all coins after loading the scene and set sensor property to YES:
coin.physicsBody.sensor = YES;
Things like this is one of the reasons I believe you first need to learn pure Cocos2D and only then use tools making your life easier such as SpriteBuilder. Which is a great tool, but in some cases you still need know what happens behind the scenes.
2. You're mixing physics with things like CGRectIntersectsRect
If you're using physics engine you need to detect collisions via collision delegate and not by checking CGRectIntersectsRect in update:.
It is hard to explain how to do this in a few sentences, so here is a nice tutorial that shows how to detect collisions in Cocos2D v3 and of course there is a chapter about this in my book.
By the way you shouldn't use update:at all when manipulating physics nodes, use fixedUpdate: instead.
I hope this will help you to solve your issue.
Related
i'm new in the development of swift ios game using spirtekit and i need help. I want to develop a vertical 2d endless run, where with a swipe you are able to move the player in direction and if there is an obstacle, it is created in a position calculate with the position of the player. Once create the obstacle i would like to make it falling down but alway with the same relation with the player (this means that it has to move only on y axis).
Can you suggest me some ideas on how to manage this?
This book teaches you exactly how to make what you are looking for:
https://www.amazon.com/Getting-Started-SpriteKit-Jorge-Jordan-ebook/dp/B01891X7TM
This is the end product:
https://itunes.apple.com/lr/app/inside-the-hat/id1076967804?mt=8
You can get it for free here (with trial):
https://www.packtpub.com/application-development/getting-started-spritekit
The source code for this is around somewhere on the web, but I forgot where :( I bought the book a year ago and can't find it now.
Basically, you have a long background that is .moveTo .. in .update you check the position of the background, then reset it based on its XY position (it basically just goes all the way down, warps to the top position, then falls)
Also in .update you check for score, or a timer, or just a random check, then spawn an enemy, obstacle, etc. You give the enemy / obstacle SKActions to move towards the player, and let .didBegin(contact:) handle scoring, sound effects, death, etc.
I have made a game using SpriteKit and Swift 3 and have figured out all aspects of the game except the speed of the ball node in the game. Im confused with the different function applyImpulse() and ball.physicsBody.velocity, as I have tested both and don't seem to really understand what the speed I'm actually programatically settings is. Any clarification on what I should be using would be great?
Also whilst testing (by printing the ball's velocity to the console every collision) I would see sometimes the ball's speed would simply go to some long and random decimal value when it hit other nodes such as a paddle which I hadn't specifically coded anything to happen with the ball's speed in the case of a collision with it.
In summary I would appreciate:
Just general clarification regarding speed of the ball in SpriteKit and how I should approach it (what method/function I should use)
How I would make it so the ball's speed doesn't got to these very long random decimals
Thanks
In regards to the values, there is not really a set rule of what the values are for impulses and forces. It depends on how big your sprites physics body are etc. An impulse of 80 might be a perfect jump value for 1 sprite size, but than make it half the size and that 80 is suddenly way to high. There are also factors such as gravity, mass etc than can have an effect on this.
So you usually just play around with the values until you get the desired result.
In regards to the collision with the paddle, you need to check your bit mask values and your dynamic properties. SpriteKit by default sets collisions to all objects, so if you dont specifically tell your paddle/ball to ignore each other they will collide.
There are also things such as restitution, friction, damping etc that can have an effect on how you sprites behave when colliding.
There are loads of tutorials on google about SpritKit physic/collisions or read the apple documentation.
In regards to the difference between velocity and impulses/forces, as per apples documentation
"First, you can control a physics body’s velocity directly, by setting its velocity and angularVelocity properties. As with many other properties, you often set these properties once when the physics body is first created and then let the physics simulation adjust them as necessary. For example, assume for a moment you are making a space-based game where a rocket ship can fire missiles. When the ship fires a missile, the missile should have a starting velocity of the ship plus an additional vector in the direction of the launch.
When a body is in the simulation, it is more common for the velocity to be adjusted based on forces applied to the body. Another source of velocity changes, collisions, is discussed later."
https://developer.apple.com/library/content/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Physics/Physics.html
So basically the general rule of thumb is this:
1) Only set the velocity property when you create the physics body. I never needed to do this for my games yet.
The only time I really use the velocity property is for things such as double jumping where I need to set it to 0 to have a consistent double jump
...velocity.dy = 0
...applyImpulse(
2) When you are playing the game already than
a) If you are trying to continuously move your ball you should use
applyForce...
in something like the update method of your SKScene.
b) If you want to make your ball jump, so basically a short 1 time thing, you should use
applyImpulse...
Hope this helps
I am making a Sprite Kit game where the player (basically a stickman) has a running animation and a parallax scrolling background.
Now I have enemies that come near my player. To destroy these enemies sometimes I have to touch the enemies node to launch a rocket or attack them with an attack button or just jump over them.
Everything is working fine, but I want to add some extra moves to destroy them. I want some enemies that you can just destroy if you have drawn a whole circle around them. So imagine they come and you make a circle and then my player launch a laser or something. The problem is I have no idea where to start.
I haven't found anything on the internet. If it's too complicated or almost impossible how about touching my player node and dragging to the enemy?
EDIT: I think I have to create a custom GestureRecognizer that recognizes if a circle is drawn around a sprite and then runs the code. I don't know how this works ?
Yes, it's too complex. Not just from a coding point of view, but also from that of the player's experience.
Anything that requires complex gestures over a large amount of glass is annoying for the player because they're never going to have the same experience. Their finger's moisture and oil content always changes, as does the ambient temperature and cleanliness of their screen.
So big gestures required to be performed quickly (a gaming input like this) will sometimes be fun and smooth, and other times degrade as an experience based on the nature of the above properties.
Best to avoid them for a game's best possible experience.
If you must do it, there's two ways to research how.
Seek out "custom gesture" creation and utilisation through documentation and google, etc.
Think about using some kind of array to store all the points where the player's finger moves through during that circle gesture and attempt to discern if an enemy is within that space and then act accordingly.
--- probably other ways, too. But these jump to mind.
I'm a little confused trying to find a reliable way to make my player-sprite jump when the user taps the screen.
So far I've been doing this:
if(self.physicsBody.velocity.dy == 0.0 && _shouldJump) {
[self.physicsBody applyImpulse: CGVectorMake(0.0, 195.0);
}
Which works, but I'm looking for something more reliable and better. Specifically, right now, the user cannot jump when he's sliding down a slope, or on the edge of a block about to fall down (because .dy isn't exactly 0). I'd like the player to be able to jump in these cases too.
I've tried something like .dy < 5.0 && .dy > -5.0, but then he's able to jump when he's at the top of his current jump, making him jump even higher.
Is there a way of checking which physicsBodies my player-sprite is in contact with maybe? Or do you have any other suggestions?
I have read Ray Wenderlich's tutorial on how to create a Platform Game Like Super Mario, but they're building their own custom Physics Engine. I'd like to stick with the one built into SpriteKit, mainly becuase of the collision handling and detection.
EDIT 1:
Bear in mind that I cannot set a flag _isOnGround = YES every time the Player touches the ground in didBeginContact, as he is bouncy and will bounce up-and-down a few times before coming to a stop. I'd prefer the user to be able to jump as soon as he touches the ground when he's holding the screen, but this is not necessary.
I am newbie in IOS Gaming, and i need to create a game using Sprite Kit framework for functionality similar to angry bird pulley system, and also wants to find the distance the object is travelled from the pulley to its landing.
Can anyone help me out with this, i would be thankfull for it.
Thanks in advance.
One way you could code a slingshot effect would to use a starting point on the screen at let's say (x=100,y=100). You would display a SpriteNode of a slingshot with the Y centered at the (100,100).
The next step would be to use touchesBegan:withEvent: in the area of the slingshot to let your code know the player is looking to shoot the slingshot.
You would use touchesMoved:withEvent: to track how far back (how much tension) the player is pulling back from the slingshot.
The release would be triggtouchesEnded:withEvent. Based on how far the touch began (x=100) and how far back is was released (for example x=30), you can apply force like this:
float forceUsed = startTouchX - endTouchX;
[_projectile.physicsBody applyForce:CGVectorMake(forceUsed, 0)];
If you are looking to angle the shot you would also have to track Y and use that variable instead of the 0 above.
As for calculating distance between 2 points on the screen, it boils down to x and y coordinates. Subtract objectA.position.x from objectB.position.x
Things can get a lot more complex of course but that all depends on what you want to do in your code. Hope this helps.
P.S. The touches above are all part of the UIResponder Class.