Setting the position of my ball - ios

I'm learning how to use SpriteKit.
Question:
As practice, I'm trying to make a mock of pong. I want the ball's initial position to be in the center, and for the life of me, I cannot set its position to be in the center. It always ends up in the bottom left hand corner of the screen and I have no clue why. I've set the scene's scale mode equal to SKSceneScaleModeAspectFill, and I've tried each of the following lines of code in separate trials in order to get set its position to the center, but it has always remained in that bottom left hand corner.
//Attempt #1
self.ball.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)); //find the middle of each axis and put them together in one coordinate
//Attempt #2
self.ball.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2); //find the width and height of the screen, divide each by 2 and assign them to an (x,y) coordinate together
//Attempt #3
self.ball.position = CGPointMake(160, 284) //Half the width and half the height
//Attempt #4
self.ball.position = CGPointMake(320, 568) //The width and the height (I'm desperately guessing at this point)
//Attempt #5
self.ball.position = CGPointMake(0,0) //I figured I'd give it a go
This ball is an SKSpriteNode by the way I didn't make a Ball subclass of SKSpriteNode or anything. The strange thing about this, is I've been able to bring up other sprites on the screen such as paddles and scores exactly where I want them. It's just this ball that isn't cooperating. What am I doing wrong? How can I prevent this issue in the future?

If you want to make ball's initial position to centre, then write below code:
[self.ball setPosition:CGPointMake(self.size.width/2, self.size.height/2)];
I'm using above code in my code and it is giving me perfect result.
Let me know it is working or not?
Happy Coding!

Related

Set permanent SKSpritenode image orientation

Hi I have a bunch of round SKSpriteNodes with a circle physical body. Now when these balls roll down a path I want some of these SKSpritenodes image to stay upright even when rolling. So think of an arrow pointing upwards. When the ball starts rolling the arrow spins in circles. But for some balls Id like the arrow to remain pointing up even when the ball rolls. Whats the best way of doing this?
Edit
So an answer was given but from testing it turns out it is not the correct one. Not allowing the ball to rotate affects the way it rolls down the path. So I guess what I want is rotation to be on but the image to always appear to the user like its not rotating. Thanks.
This looks like a job for SupermSKConstraint. Constraints are evaluated and applied after the physics simulation runs on each frame, so you can use them for tasks like making a node point a certain direction regardless of what physics does to it. For this, you'd want a zRotation constraint.
But there's a bit more to it than that. If you set a zero-rotation constraint on the ball:
// Swift
let constraint = SKConstraint.zRotation(SKRange(constantValue: 0))
ball.constraints = [constraint]
You'll find that SpriteKit resets the physics body's transform every frame due to the constraint, so it only sort-of behaves like it's rolling. Probably not what you want. (To get a better idea what's going on here, try adding a zero-rotation constraint to a rectangular physics body in a world without gravity, applying an angular impulse to it, and watching it try to spin in a view with showsPhysics turned on. You'll see the sprite and its physics body get out of sync and shake a bit -- probably due to accumulated rounding errors as the physics engine and the constraint engine fight it out.)
Instead, you can do a bit of what's in 0x141E's answer, but use constraints to make it less code (and run more efficiently):
Give the ball node a circular physics body. (And possibly no texture, if the only art you want for the ball is a non-rotating sprite.)
Add the arrow node as a child of the ball node. (It doesn't need its own physics body.)
Put a zero-rotation constraint on the arrow.
Wait, that doesn't work -- I told the arrow to not rotate, but it's still spinning?! Remember that child nodes are positioned (and rotated and scaled) relative to their parent node. So the arrow isn't spinning relative to the ball, but the ball is spinning. Don't worry, you can still solve this with a constraint:
Tell the constraint to operate relative to the node containing the ball (probably the scene).
Now the constraint will keep the arrow in place while allowing the ball to rotate however the physics simulation wants it to.
Here's some test code to illustrate:
// Step 1: A rectangular spinner so we can see the rotation
// more easily than with a ball
let spinner = SKSpriteNode(color: SKColor.redColor(), size: CGSize(width: 300, height: 20))
spinner.position.x = scene.frame.midX
spinner.position.y = scene.frame.midY
spinner.physicsBody = SKPhysicsBody(rectangleOfSize: spinner.size)
scene.addChild(spinner)
spinner.physicsBody?.applyAngularImpulse(0.1) // wheeeeee
// Step 2: Make the arrow a child of the spinner
let arrow = SKSpriteNode(color: SKColor.greenColor(), size: CGSize(width: 20, height: 50))
spinner.addChild(arrow)
// Step 3: Constrain the arrow's rotation...
let constraint = SKConstraint.zRotation(SKRange(constantValue: 0))
arrow.constraints = [constraint]
// Step 4: ...relative to the scene, instead of to its parent
constraint.referenceNode = scene
Here are two methods to create a ball with a physics body and an arrow:
Add an arrow as a child of a ball
Add both the ball and the arrow directly to the scene
Here's what will happen when you add the above to the SpriteKit simulation:
The arrow will rotate when the ball rotates
Both the arrow and the ball will move/rotate independently
If you want the arrow to rotate with the ball, choose Option 1. If you want the arrow to remain fixed, choose Option 2. If you choose Option 2, you will need to adjust the rotation of the arrow to ensure that it points upward. Here's an example of how to do that.
-(void)didMoveToView:(SKView *)view {
self.scaleMode = SKSceneScaleModeResizeFill;
/* Create an edge around the scene */
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:view.frame];
// Show outline of all physics bodies
self.view.showsPhysics = YES;
CGFloat radius = 16;
SKNode *balls = [SKNode node];
balls.name = #"balls";
[self addChild:balls];
// Create 5 balls with stationary arrows
for (int i = 0;i<5;i++) {
// Create a shape node with a circular physics body. If you are targeting iOS 8,
// you have other options to create circular node. You can also create an SKSpriteNode
// with a texture
SKShapeNode *ball = [SKShapeNode node];
// Create a CGPath that is centered
ball.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(-radius,-radius,radius*2,radius*2)].CGPath;
ball.fillColor = [SKColor whiteColor];
ball.position = CGPointMake(100, 100+i*radius*2);
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:radius];
[balls addChild:ball];
// Create an arrow node
CGSize size = CGSizeMake(2, radius*2);
SKSpriteNode *arrow = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:size];
arrow.name = #"arrow";
arrow.position = CGPointZero;
[ball addChild:arrow];
// Apply angular impulse to the ball so it spins when it hits the floor
[ball.physicsBody applyAngularImpulse:-1];
}
}
- (void) didSimulatePhysics
{
SKNode *balls = [self childNodeWithName:#"balls"];
for (SKNode *ball in balls.children) {
SKNode *arrow = [ball childNodeWithName:#"arrow"];
arrow.zRotation = -ball.zRotation;
}
}
sprite.physicsBody.allowsRotation = NO;
The allowRotation property should control exactly what you are asking.

Trouble with anchor point in CGAffineTransformScale

I'm trying to get a UIButton to scale but remain at its original center point, and I'm getting perplexing results with CGAffineTransformScale.
Here's the function in my UIButton subclass:
-(void)shrink {
self.transform = CGAffineTransformMakeScale(0.9,0.9);
}
With this code, the button scales to the top-left corner, but when I add code to try to set the anchor point (either of the following lines), the button gets relocated off screen somewhere:
[self.layer setAnchorPoint:CGPointMake(self.frame.size.width/2, self.frame.size.height/2)];
//same result if I use bounds instead of frame
[self.layer setAnchorPoint:self.center];
Interestingly, this line causes the view to move down and to the right some distance:
[self.layer setAnchorPoint:CGPointMake(0, 0)];
Sorry, I know there are many posts on this topic already but I honestly read and tried at least a dozen and still couldn't get this to work. I'm probably just missing something incredibly simple.
The default anchor point is 0.5, 0.5. That is why setting it to 0, 0 moves the view down and to the right. Also, if you don't want the center to move, you need to re-adjust the center after scaling it.
Just readjust its position after shrinking it.
-(void)shrink {
CGPoint centerPoint = self.center;
self.transform = CGAffineTransformMakeScale(0.9,0.9);
self.center = centerPoint;
}

SKPhysicBody In the Wrong position

I am creating a simple Sprite Kit game however when i am adding the PhysicsBody to one of my sprites it seems to be going in the wrong position. i know that it is in the wrong position as i have have set
skView.showsPhysics = YES;
and it is showing up in the wrong position.
The Square in the bottom corner is the physics body for the first semicircle. I am using a square at the moment just for testing purposes.
My app includes view following and follows my main sprite when it moves. I implemented this by following apples documentation and creating a 'myworld' node and creating all other nodes from that node.
myWorld = [SKNode node];
[self addChild:myWorld];
semicircle = [SKSpriteNode spriteNodeWithImageNamed:#"SEMICRICLE.png"];
semicircle.size = CGSizeMake(semicircle.frame.size.width/10, semicircle.frame.size.height/10);
semicircle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:semicircle.frame.size];
semicircle.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
semicircle.physicsBody.dynamic = YES;
semicircle.physicsBody.collisionBitMask = 0;
semicircle.name = #"semicircle";
[myWorld addChild:semicircle];
To centre on the node I call these methods
- (void)didSimulatePhysics
{
[self centerOnNode: [self childNodeWithName: #"//mainball"]];
}
- (void) centerOnNode: (SKNode *) node
{
CGPoint cameraPositionInScene = [node.scene convertPoint:node.position fromNode:node.parent];
node.parent.position = CGPointMake(node.parent.position.x - cameraPositionInScene.x, node.parent.position.y - cameraPositionInScene.y);
}
I don't know if the my world thing makes any difference to the SkPhysics body...
SKPhysicsBody starts at coordinates 0,0 which is at the bottom left hand corner. If you make the area smaller, as you did by width/10 and height/10, you decrease the size but from the bottom left.
I think what you are looking for is bodyWithRectangleOfSize:center: which allows you to manually set the center from which you base your physics body area on.
Update:
Based on what I understand, your smallest semi circle pic size is the same as the screen size. I would suggest you modify the image size to something like the example I have. You can then set the sprite's position as required and set the physics body to the half of the image containing your semi circle.
Your centerOnNode call should be put in the didEvaluateActions function instead of the didSimulatePhysics function. This is because you need to move the world before the physics are drawn so that they stay in sync. Similar question found here: https://stackoverflow.com/a/24804793/5062806

Scale CCSprite from bottom right hand corner

So here's the gist of what I'm trying to do here.
I have an array of foreground sprites that I scroll forever as the player moves along. What I would like to do, is when the player starts passing a certain point on the Y axis, scale down those foreground sprites while still moving them.
I'd like to be able to scale the sprites from their bottom left hand corners when the player is going up, and I've got this working without any problems.
The real problem is that I'd also like to scale the sprites from their bottom right hand corners when the player is coming down. Now I thought that I could do this by setting each sprite's anchor point to 1,0 before scaling it, but that doesn't seem to work. The sprites still scale from their bottom left hand corners.
What am I missing here?
// do logic to identify the scale factor we want
for (CCSprite *sprite in foreground_sprites)
{
CGPoint old_anchor = sprite.anchorPoint;
[sprite setAnchorPoint:ccp(1,0)];
[sprite setScale:scale_factor];
[sprite setAnchorPoint:old_anchor];
}
Have you tried messing with this property?
ignoreAnchorPointForPosition(false);
I'm using cocos2d-x, there should be something similar to that
If I understand correctly, you want to scale from the bottom left while the player's Y position increases but scale using the bottom right while they are descending?
Well you can't just change the anchor point alone. The anchor point and position go hand in hand to position the sprite on the screen. So if you positioned the sprite on to the screen using an anchor point of (0,0) then if you want to switch it's anchor point to (1,0) while keeping it in the same location on the screen, you'll need to update the position.
CCSprite* sprite = ...;
sprite.anchorPoint = CGPointZero;
sprite.position = CGPointZero;
...
sprite.anchorPoint = CGPointMake(1.0f, 0.0f);
sprite.position = CGPointMake(sprite.position.x + (sprite.contentSize.width * sprite.scaleX * sprite.anchorPoint.x),
sprite.position.y + (sprite.contentSize.height * sprite.scaleY * sprite.anchorPoint.y));
Hopefully I understood your problem correctly and was able to help.

rotate a sprite around an anchor point

I have a sprite :
ombreoeuf1 = [CCSprite spriteWithFile:#"mangeurcentremieu3_03.png" ];
ombreoeuf1.position = ccp(240,160);
[self addChild:ombreoeuf1];
And I would like to rotate it constantly around an anchor point. How can I do it?
You can first set anchor point by setting the property anchorPoint, for example:
[ombreoeuf1 setAnchorPoint:ccp(0,0)]
and then set rotation (in degrees) by setting another property rotation:
[ombreoeuf1 setRotation:90]
anchorPoint and rotation are both properties of CCNode class, which is the parent of CCSprite.
Update
According to your comments, it seems that what you want is a rotating sprite which never stops? Here is an example which let the sprite rotate 10 degrees per 0.1 seconds:
[sprite runAction:[CCRepeatForever actionWithAction:[CCRotateBy actionWithDuration:0.1 angle:10]]];
All transformations of CCNode subclasses are done relatively to the anchor point. During all of your transformations the anchorPoint will have the same position. For example, if you will place sprite with anchorPoint (0.f, 0.f) to the position (0.f, 0.f), the left-bottom corner of the screen, then set it's scale, for example, to 5.f, after transforming it will stay at the left-bottom corner, just wil become larger. So all rotations automatically will be done relatively to the anchor point.
Just one more thing. CCSprite has anchorPoint (0.5f, 0.5f) by default and some content size, so you just have to set it to another to see changes in transformations. If you want to do it with CCNode, you have to set it's relativeToAnchorPoint property to YES and set contentSize manually.
You can use CCRepeatForever action for this. For example,
id rotateAction = [CCRepeatForever actionWithAction:[CCRotateBy actionWithDuration: yourDuration
angle: anyAngleForGivenTime]];

Resources