Sprite-kit - Facing the hero? ( rotating to the direction of another node) - objective-c

I have two spriteNodes hero and the enemy, both with rectangular physicsBody applied.
In the update, when the hero gets to the certain point, e.g hero.position.y <= 300 I want the enemy to rotate and face the the hero as it moves down.
the only sample code I found was the Adventure from Apple which has a faceTo class but I found it very complicated to use. I am looking for a nice and clean solution for it.
Thanks in advance.

The most basic implementation should look something like this:
- (void)rotateNode:(SKNode *)nodeA toFaceNode:(SKNode *)nodeB {
CGFloat angle = atan2f(nodeB.position.y - nodeA.position.y, nodeB.position.x - nodeA.position.x);
if (nodeA.zRotation < 0) {
nodeA.zRotation = nodeA.zRotation + M_PI * 2;
}
[nodeA runAction:[SKAction rotateToAngle:angle duration:0]];
}
It's important that you understand what is happening. Look up and read about atan2 (http://en.wikipedia.org/wiki/Atan2) and try to understand how the code above works.

You can use the xScale property of SKNode to make the sprite face the other way. This can be done by setting:
sprite.xScale = -1.0;
However, this has been proved to cause problems with the physicsBody, as can be seen from this question:
Flipped x-scale breaks collision handling (SpriteKit 7.1)
The solution for this problem is given there itself by JKallio.
He suggests keeping your sprite as a child of another SKNode (to which you apply the physicsBody) and changing the xScale property of the child node where needed. This is what I am using in my own project as well.

Related

libgdx camera position using viewport

I am rather experiences libgdx developer but I struggle with one issue for some time so I decided to ask here.
I use FillViewport, TiledMap, Scene2d and OrtographicCamera. I want the camera to follow my player instance but there are bounds defined (equal to mapsize). It means that camera will never ever leave outside of map, so when player comes to an end of the map camera stops following and he goes to the edge of the screen itself. Maybe sounds complicated but it's simple and I am sure that you know what I mean, it's used in every game.
I calculated 4 values:
minCameraX = camera.viewportWidth / 2;
minCameraY = camera.viewportHeight / 2;
maxCameraX = mapSize.x camera.viewportWidth / 2;
maxCameraY = mapSize.y - camera.viewportHeight / 2;
I removed not necessary stuff like unit conversion, camera.zoom etc. Then I set the camera position like this:
camera.position.set(Math.min(maxCameraX, Math.max(posX, minCameraX)), Math.min(maxCameraY, Math.max(posY, minCameraY)), 0);
(posX, posY is player position) which is basically setting camera to player position but if it's to high or too low it sets it to max or min defined before in right axis. (I also tries MathUtils.clamp() and it works the same.
Everything is perfect until now. Problem occures when aspect ratio changes. By default I use 1280x768 but my phone has 1280x720. Because of that bottom and top edges of the screen are cut off because of the way how FillViewport works. Because of that part of my map is cut off.
I tried to modify maximums and minimums, calculate differences in ratio and adding them to calculations, changing camera size, different viewports and some other stuff but without success.
Can you guys help?
Thanks
I tried solution of noone and Tenfour04 from comments above. Both are not perfect but I am satisified enough i guess:
noone:
camera.position.x = MathUtils.clamp(camera.position.x, screenWidth/2 + leftGutter, UnitConverter.toBox2dUnits(mapSize.x) - screenWidth/2 + rightGutter);
camera.position.y = MathUtils.clamp(camera.position.y, screenHeight/2 + bottomGutter, UnitConverter.toBox2dUnits(mapSize.y) - screenHeight/2 - topGutter);
It worked however only for small spectrum of resolutions. For strange resolutions where aspect ratio is much different than default one I've seen white stripes after border. It means that whole border was printer and some part of the world outside of border. I don't know why
Tenfour04:
I changed viewport to ExtendViewport. Nothing is cut off but in different aspect ratios I also can see world outside of borders.
Solution for both is to clear screen with same color as the border is and background of level separatly which gave satisfying effect in both cases.
It stil has some limitations. As border is part of the world (tiled blocks) it's ok when it has same color. In case border has different colors, rendering one color outside of borders won't be a solution.
Thanks noone and Tenfour04 and I am still opened for suggestions:)
Here are some screenshots:
https://www.dropbox.com/sh/00h947wkzo73zxa/AAADHehAF4WI8aJ8bu4YzB9Va?dl=0
Why don't you use FitViewport instead of FullViewport? That way it won't cut off your screen, right?
It is a little bit late, but I have a solution for you without compromises!
Here width and height are world size in pixels. I use this code with FillViewport and everything works excellent!
float playerX = player.getBody().getPosition().x*PPM;
float playerY = player.getBody().getPosition().y*PPM;
float visibleW = viewport.getWorldWidth()/2 + (float)viewport.getScreenX()/(float)viewport.getScreenWidth()*viewport.getWorldWidth();//half of world visible
float visibleH = viewport.getWorldHeight()/2 + (float)viewport.getScreenY()/(float)viewport.getScreenHeight()*viewport.getWorldHeight();
float cameraPosx=0;
float cameraPosy=0;
if(playerX<visibleW){
cameraPosx = visibleW;
}
else if(playerX>width-visibleW){
cameraPosx = width-visibleW;
}
else{
cameraPosx = playerX;
}
if(playerY<visibleH){
cameraPosy = visibleH;
}
else if(playerY>height-visibleH){
cameraPosy = height-visibleH;
}
else{
cameraPosy = playerY;
}
camera.position.set(cameraPosx,cameraPosy,0);
camera.update();

physicsBody rotation limitation

I've got the following node set as follow.
box.physicsBody.allowsRotation = YES;
No mater what force applies to this box, I want it to never fall down or rotate more than a certain angle, just like a tree or a spring that might bend all the way down but has a tendency to go back to it's initial angle or position.
Is there a any trick or method to that?
I was thinking maybe joining an invisible un-rotatable physics body under the box and use a joint spring method for that which I have no Idea how that works!
Or, maybe there be a trick to play with the pivot. Any idea?
In the update: method you will have to continuously check the desired node's properties. In your case it is going to be the zRotation property of your node.
Add this code in your update: method:
if(yourNode.zRotation > 0.5)
yourNode.zRotation = 0.5;
if(yourNode.zRotation < -0.5)
yourNode.zRotation = -0.5;
Change the 0.5 value to your desired value or replace it with a static const float.

Dynamic resizing of the body (LibGDX)

I have a circle-shaped dynamic body and I need to resize it during the game (It appears like a point, then it grows to a circle and after that it starts moving). How should I do that?
I have an idea - it's to use some animation (Circle has the same radius, but due to animation it looks like the circle grows), but I'm not sure if it's right way or not. (Besides I don't know how to realize it)
For scaling circle, if you are using sprite just scale it sprite.setScale(float), if your sprite is attached to Box2d Circle-shape then get the Body's shape and set the radius
Shape shape = body.getFixture().getShape;
shape.setRadius(radiusValue);
and if you are using ShapeRenderer just multiply the points of ShapeRenderer.
I assume that you are talking about a Box2D body.
It is not possible to change a circle-shaped fixture with Box2D. Box2D is a rigid body simulator. What you would have to do is destroy the fixture and replace it with a smaller/bigger version of the circle. But this will cause a lot of problems, since you cannot destroy a fixture when there is still a contact for example.
It would be better to keep the circle the same size and just simulate a change in size with an animation of a texture on top.
If you cannot simulate that, then maybe try the following approach: Have several versions of that circle in different sizes and keep them on top of each other. Implement a ContactFilter which will only cause contacts for the one circle which is currently "active".
Inside any Object class with box2d, I use the following for dynamic resizing:
public void resize(float newradius) {
this.body.destroyFixture(this.fixture);
fixtureDef.density = (float) (this.mass/(Math.PI*newradius*newradius));
this.radius = newradius;
CircleShape circle = new CircleShape();
circle.setRadius(newradius);
this.fixtureDef.shape = circle;
circle.dispose();
this.fixture = body.createFixture(fixtureDef);
this.fixture.setUserData(this);
}
You can also see the following topic: How to change size after it has been created

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

iOS Pong Development, Collision Detection

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.