iOS Pong Development, Collision Detection - objective-c

I am in a late phase of finishing my first usable iOS app.
I am creating a simple Pong game i am using a simple collision detection using CGRectIntersectsRect, but i came up with a problem.
if(CGRectIntersectsRect(mic.frame,plosina_a.frame)) {
if(mic.center.y < (plosina_a.center.y + plosina_a.frame.size.height)) {
RychlostMice.y = -RychlostMice.y;
}
}
if(CGRectIntersectsRect(mic.frame,plosina_b.frame)) {
if(mic.center.y < (plosina_b.center.y + plosina_b.frame.size.height)) {
RychlostMice.y = -RychlostMice.y;
}
}
When i use it like this the ball (mic) sort of gets to the paddles (plosina) and starts moving the other way sort of in the middle of the paddle.
My programming teacher managed to fix this problem for one of the paddles (the _b one) by adding the .frame.size.height instead of just .frame which i have used before, but when i did the same thing for the other paddle it didn't work i don't know what's up with that.
Also it creates another problem sometimes there is a situation where the ball get's caught up in the paddle - so I'm looking for a definition of the whole object and not just one side probably?
i hope you can help.

I can see three potential problems here.
The first is that you are waiting until the ball overlaps the paddle before counting it as a touch. It sounds like you really want to start the ball moving in the other direction when the ball touches the paddle, not when it intersects it. The CGRectIntersectsRect waits until they overlap before returning true. If you make either rectangle one pixel larger with a call to CGRectInset, your test will return true as soon as the ball reaches that paddle--by that time, there will be one pixel overlapping the expand rectangle. The test would look like this:
if(CGRectIntersectsRect(CGRectInset(mic.frame, -1, -1),plosina_a.frame)) {
if(mic.center.y < (plosina_a.center.y + plosina_a.frame.size.height)) {
RychlostMice.y = -RychlostMice.y;
}
}
if(CGRectIntersectsRect(CGRectInset(mic.frame, -1, -1),plosina_b.frame)) {
if(mic.center.y < (plosina_b.center.y + plosina_b.frame.size.height)) {
RychlostMice.y = -RychlostMice.y;
}
}
The second potential problem has to do with the velocity of the ball. Without seeing all of the code, I don't know if this is a problem or not. If the ball can move more than one pixel at a time, it could easily overlap--or even pass through--the paddle without a hit detection. There are lots of logic changes you can add to take care of this, but the easiest solution may be to just make sure the ball doesn't move more than one pixel at a time.
Finally, if you want to use the hack for both paddles, reverse the sign of the comparison on the other side of the game.

I'm guessing that your pong is played vertically, so that one paddle is at the top of the screen and the other is at the bottom?
If you you need to mirror the logic vertically for the other paddle. Right now you are using the same logic for the top and bottom paddles, but for the bottom paddle you probably need something like the following instead
if(CGRectIntersectsRect(mic.frame,plosina_b.frame)) {
if(mic.center.y > (plosina_b.center.y - plosina_b.frame.size.height)) {
RychlostMice.y = -RychlostMice.y;
}
}
Notice how I'm using the > sign and subtracting the height instead of adding it.

Related

How to fix: code not running on certain frames

I have been trying to make my character shoot a projectile on a particular frame of animation. However, sometimes it works and other times it just ignores creating the projectile.
I've tried using alarms instead of checking for the image index but I can't get the timer low enough to get the perfect timing.
I think it may be a problem with the image speed being 0.2 instead of 1.
I'm using a state machine to make it switch between moving and shooting, but I checked and it isn't a problem with state switching over as it changes when I want it to.
Here is relevant code from the shooting state:
if image_index == 2 {
instance_create(x+20*image_xscale,y,obj_projectile);
}
Here is the code that changes the tank over to the shooting state from the main state:
if key_shoot{
state = states.shoot;
image_speed = 0.2;
sprite_index = spr_tankShoot;
}
There is also an animation end event in the object with the following code:
if sprite_index == spr_tankShoot{
state = states.normal;
}
If anyone can see something wrong with the code and/or know what might be going wrong with this, it'd be much appreciated.
I think it may be a problem with the image speed being 0.2 instead of 1.
This is possible - if your animations have different speeds and you don't tend to reset image_index on animation start, you may end up with varying starting indexes (suppose, 0.1) that would not fall right on 2.0 when adding 0.2 to them. Checking that a frame is precisely a number is a not-as-good practice in general though.
You could store image_index at the end of the frame for future reference,
image_index_previous = image_index;
and then check that image_index stepped over 2 since the last frame:
if image_index_previous < 2 && image_index >= 2 {
instance_create(x+20*image_xscale,y,obj_projectile);
}

Sprite in Game Maker doesn't act the way I want it to

I'm currently working on animating my player so that he behaves like he's breathing.
if(time mod 60==0){
if(image_index==0){
image_index=1;
}
else{
image_index=0;
}
}
time++;
The whole thing is put in the step event and sprite is changing every single step and it even changes to an index 2 and 3, which I haven't even used in the code.
So if anyone has some ideas why does it work like this then please tell me.
It is because the sprite you use has multiple sub-images. GameMaker will naturally iterate the image index every frame.
So first, you need to stop the animation from running with
image_speed = 0;
You have to run this line when the sprite has just been changed, so ideally just after the "sprite_index" variable is changed. If you don't change it, just set image_speed to zero in the creation code.
If you are curious, I found the answer here : How to freeze sprite animation on last frame?

Stopping nodes to exact positions

I have a node moving on the screen with a velocity of 400pps. I would like to stop the node when it reaches a precise location on the screen. I am doing so by setting the node velocity to 0 in the update cycle.
However, the node moves pass the desired point by an unpredictable amount, and stops somewhere later.
I suspect the problem is in the response time. Simply put, the physic engine is not quick enough to stop the node accurately. My app is running at 30fps on my Mac and 60fps on iPhone 5S.
What is the best way to achieve accurate node movements and stopping? I suppose I could reposition the node to the desired location after I stop it, but that would probably mess up the all physic world.
This is how the relevant part of my update method looks like:
- (void)update:(NSTimeInterval)currentTime {
// Start moving
if(verticalScrollSpeed) {
node.physicsBody.velocity = CGVectorMake(0, verticalScrollSpeed);
}
// Stop moving
if(verticalScrollSpeed > 0 && obstaclesContainerNode.position.y >= 0) {
verticalScrollSpeed = 0;
node.physicsBody.velocity = CGVectorMake(0, 0);
}
}
You would have to cheat a little. Nothing is really "moving" in a game. everything is just kinda teleporting however many pixels per frame. If something is moving extremely fast you may overshoot. The best you can do is something like this
if distanceToTarget <= 1 {
yourNode.position = targetNode.position
}
The other thing you can consider is slowing down your node as it gets closer to the other one. That would make arrival more accurate.. but that may or may not be something you want for your game.

looping a sprite vertically objective C sprite builder

Note: for this I am using a program called spritebuilder, which allows me to create a game with less code than would normally be needed. If you know a solution that's just all code, then by all means feel free to share it :)
Also, for this question, I followed a tutorial at this link: Build Your Own Flappy Bird Clone. Just scroll down to the part that says: "Loop the Ground"
So here's my problem. Im currently working on a game, and I created a camera which scrolls vertically long with the character sprite i created, however i need a certain image to loop. When the image leaves the bottom part of the screen I would like it to loop around to the top of the screen, infinitely. For this i created two identical images (in this case its the bark of a tree). One will be on screen, while the other will be offscreen, so as the first image leaves the screen, the second will replace it (seamlessly). I created two objects for the images, and assigned them the name _ground1, and _ground2, and I also created an NSArray in which to store them in. (Please refer to the link above if it is somewhat confusing)
Here is the code that I have:
CCNode *_ground1;
CCNode *_ground2;
NSArray *_grounds;
for (CCNode *ground in _grounds) {
// get the world position of the ground
CGPoint groundWorldPosition = [_physicsNode convertToWorldSpace:ground.position];
// get the screen position of the ground
CGPoint groundScreenPosition = [self convertToNodeSpace:groundWorldPosition];
// if the left corner is one complete width off the screen, move it to the right
if (groundScreenPosition.y <(-1 * ground.contentSize.height)) {
ground.position = ccp(ground.position.x , ground.position.y + 2 * ground.contentSize.height);
}
For some reason when I try this, it doesnt seem to work. what happens is that, the camera will travel vertically as it is meant to do, but the images do not loop. Once the two images leave the bottom of the screen, no new images replace them.
i also done this project as above tutorials. it work fine but you have some mistake to set variable in spritebuilder. in your above code replce code as and try it. you only put less than may be it issue.
if (groundScreenPosition.y <=(-1 * ground.contentSize.height)) {
ground.position = ccp(ground.position.x , ground.position.y + 2 * ground.contentSize.height);
}
You are using CCNode objects as _ground1and _ground2.
CCNode objects usually do not have a contentSize, they will return 0 unless you explicitly set them inSpriteBuilder`.
Make sure that you are using CCSprite objects in SpriteBuilder and in your code.
Also, as a friendly hint you should also consider refactoring (renaming) your sprites with more meaningful names for your use case like _treeBark1 and treeBark2 for example.

Variable Jump Height

I have been having great difficulty creating a jumping system whereby the user can tap the jump button for a small jump and hold it down for a higher jump.
I stumbled upon this topic:
https://gamedev.stackexchange.com/questions/13277/variable-height-jumping-in-side-scrollers
Which greatly helped me develop the following code:
PlayerMovementTimer = [NSTimer scheduledTimerWithTimeInterval:0.005 target:self selector:#selector(movePlayer) userInfo:nil repeats:YES];
[JumpButton addTarget:self action:#selector(jumpPlayer:) forControlEvents:UIControlEventTouchDown];
[JumpButton addTarget:self action:#selector(stopJump:) forControlEvents:UIControlEventTouchCancel | UIControlEventTouchUpInside | UIControlEventTouchDragExit];
- (void)movePlayer
{
CGFloat playerY = Player.center.y + PlayerYV;
if(playerY > 264) {
PlayerYV = 0;
playerY = 264;
}
if(playerY < 264) {
PlayerYV += 0.048f - PlayerYD;
}
if(HoldingJump && PlayerYV < 0 && PlayerYD + 0.0018f < 0.048f) {
PlayerYD += 0.0018f;
}
Player.center = CGPointMake(Player.center.x + PlayerXV, playerY);
}
- (IBAction)jumpPlayer:(id)sender
{
if(Player.center.y == 264) {
PlayerYD = 0;
PlayerYV = -2.25;
HoldingJump = true;
}
}
- (IBAction)stopJump:(id)sender
{
HoldingJump = false;
}
The code seems to work (some of the values need a bit of fine tuning but I haven't gotten round to that yet). The only problem is that the movement appears to be slightly jerky (even on the real device) and that when the player is at the top of the jump they accelerate really slowly and no values I put seem to be able to get the jump to look smooth like on Mario games.
Please take a look at the code and see if I am missing something obvious, or if there is a more efficient method of controlling movement than an NSTimer calling a void function. Also, is setting a UIImageView's position to a float value bad?
Thanks.
So there are quite a few things wrong here. First, yes, you should never be setting the origin of an ImageView or any other UI element to a coordinate position that is a fractional pixel. This causes sub-pixelling which will blur your image. To avoid this, all CGFloats should be rounded to the nearest whole number using roundf() or other similar rounding functions.
Another issue I can see is that you're setting Player.center. I hope for your sake that Player is not an ImageView cause you're going to be making your life harder. As mentioned above, when the origin of a frame is not set to a CGFloat that is a round number, you'll get sub-pixelling. When you use the center property, you can easily cause yourself to get on a bad origin value. For example, if I have a 11 by 11 image and set it's center to (11,11), the origin will get set to (5.5,5.5) and will cause sub-pixelling. Easy ways to avoid this is just do the math to place the origin correctly and make sure to round the CGFloats that you feed into it (or use CGRectIntegral on the frame before you set it).
A third issue here is that the timer is being called 0.005 seconds. Let's assume you want this game to run with 60 FPS. 60 FPS translates to about 0.0167 seconds. The timer is calling the method three times more often then it would need to even if you wanted 60 FPS and additionally, calling this method so often could be causing some of your jerky motion.
Now in terms of getting a "Mario" like jump, what you really need to do is look at getting a dedicated physics engine since if you're using the code above, you don't appear to have one. What a physics engine would do is it would apply a constant "gravity" which will help make the player jumps look and act more realistically. You would, when a player presses a button, apply an impulse up on the player character. The use of impulses would also simplify your work as you could apply impulses in different ways depending on how long they hold the button, etc. The code above is simply trying to get around this problem instead of addressing the real issue of you not having a physics engine.
Go investigate cocos2D and Box2D as a possible physics engine you could use. There are a wealth of resources on cocos2D+Box2D and there is a developer who even has made a tutorial on using cocos2D to create a Super Mario clone that should give you some basic understanding of how physics engines work: http://www.raywenderlich.com/15230/how-to-make-a-platform-game-like-super-mario-brothers-part-1