SpriteKit - How to make applyImpuse always the same force - objective-c

I am working on a game where my hero will be able to jump. I can do that with applyImpulse easy enough. The problem I'm having is I want him to be able to double jump and sometimes triple jump. When he does a double jump, sometimes he goes REALLY high. Way higher than the first jump. I want his jump to be equal each time he does it and I want him to go down at the same speed that he went up.
I am using this for the jump:
[hero.physicsBody applyImpulse:CGVectorMake(0, 120)];
I don't have a lot of physicsWorld defined which might be my issue. I have the following set:
self.physicsWorld.contactDelegate = self;
self.physicsWorld.gravity = CGVectorMake(0, -10.0);
I've tried different gravity's but it comes out the same.
My hero has the following properties:
hero.physicsBody.friction = 1.0f;
hero.physicsBody.restitution = 0.0f;
hero.physicsBody.linearDamping = 0.1f;
hero.physicsBody.allowsRotation = NO;
hero.physicsBody.mass = 0.2f;
Is there something here that would be causing my issue? Something I'm missing or I should try?

That's how physics works. A way around it is to reset hero's velocity right before you apply the second impulse.
hero.physicsBody.velocity = CGVectorMake(0, 0);
[hero.physicsBody applyImpulse:CGVectorMake(0, 120)];

Related

Scenekit: Objects become invisible after several objects are added (Objective-C)

I am building a game with SceneKit. It is based on SCNBoxes which get added and removed. At the end there are like 30 boxes added to the root node.
// Prepare Surface Layer for Blocks
self.colorOfBlock = [CALayer layer];
self.colorOfBlock.frame = CGRectMake(0, 0, 1000, 1000);
self.colorOfBlock.backgroundColor = [UIColor colorWithHue:0 saturation:1 brightness:1 alpha:1].CGColor;
self.textLayer = [CATextLayer layer];
self.textLayer.frame = self.colorOfBlock.bounds;
self.textLayer.fontSize = 750;//self.colorOfBlock.bounds.size.height;
self.textLayer.string = #"2";
self.textLayer.alignmentMode = kCAAlignmentCenter;
self.textLayer.foregroundColor = [UIColor blackColor].CGColor;
[self.textLayer display];
[self.colorOfBlock addSublayer:self.textLayer];
// Prepare Material for the Block
SCNMaterial *material = [SCNMaterial material];
material.diffuse.contents = self.colorOfBlock;
// Create the Block
self.blockNode = [SCNNode node];
self.blockNode.geometry = [SCNBox boxWithWidth:0.95 height:0.95 length:0.95 chamferRadius:0.1];
self.blockNode.geometry.firstMaterial = material;
self.blockNode.position = position;
// Setup the physics body
self.blockNode.physicsBody = [SCNPhysicsBody dynamicBody];
self.blockNode.physicsBody.affectedByGravity = NO;
self.blockNode.physicsBody.categoryBitMask = CollisionCategoryBlock;
self.blockNode.physicsBody.contactTestBitMask = CollisionCategoryBorder | CollisionCategoryBlock;
self.blockNode.physicsBody.collisionBitMask = CollisionCategoryBorder | CollisionCategoryBlock;
self.blockNode.physicsBody.angularVelocityFactor = SCNVector3Make(0, 0, 0);
[self addChildNode:self.blockNode];
self.gameValue = 2;
if (position.z < 1) {
self.name = #"Front";
} else {
self.name = #"Back";
}
After a while the textLayer seem to disappear. If new blocks are added, they have no textLayer anymore. And another side effect is that old textLayers on the existing blocks are not updated anymore.
On the next step newly added blocks become invisible. Or better to say - they never get a CALayer. But the physicsBodies are still working.
And sometimes the view crashes. The debugger says something like the position of the crashing area can not be found. After this the view is deformed. But I still can call SCNActions that clears the view and shows up all created Objects that are NOT these blocks like I posted. These blocks are totally kicked out of the view.
By the way when I setup the "phonglighttype" for those blocks this bugging cascade happens earlier.
There is also one more thing I noticed. When I tab out of the App (tested from iPhone 5) and tabbed in again after a while, the
self.gameView.showsStatistics = YES;
shows on the GPU bar a blue line. After 2 or 3 sec, the blue bar is gone and a full green GPU bar shows that it is ready for getting used. And everything works like it should do. After a while these blocks become invisible again. If I tab out and tab in again, newly added Blocks are visible again.
Somehow I think of that I am spamming my device cache until the App crashes. But there is no useful hint from Xcode. I wonder if an option to clear the viewControllers cache might solve this problem - if there is an option for this.
Kind Regards
I did not solved it completely, but I decided to replace every part of CALayer and CATextLayer with a common
material.diffuse.contents = [arrayOfTextures objectAtIndex:certainImage];
With a higher resolution (like Iphone 6 has) it did show up that the CALayer was causing some kind of graphical faulting. But the simple pre-worked image (from an imageArray) solution improves the performance pretty much and prevents from crashing.
I can not surely say if there is no way to solve it with the CALayer approach. But loading images as Material and updating them brought the most satisfying result.

how to stop a sprite from leaving the screen

I am using the accelerometer to move a sprite around the screen but I don't want to leave the screen.
I try with this
self.physicsWorld.contactDelegate = self;
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsBody.categoryBitMask = edgeCategory;
sprite.physicsBody.collisionBitMask = edgeCategory;
But the sprite still leaves the screen
I also change the scene anchor point
self.anchorPoint = CGPointMake(0.5, 0.5);
Try creating 4 rectangle SpriteNodes and making them very thin, long lines that make up your border. Give them all the same CategoryBitMask, etc.
This way, You can set the roof and floor using self.size.width as the length and around 1 or two as the thickness. Opposite for the Sides.
This will ignore the problem I think you are having where the scenes physicsBody rectangle is not centered to the middle of the screen.
If you did not previously do this, using your method:
Set sprite.categorybBitMask = spriteCategory;
Set self.collsionBitMask = spriteCategory;
one of the nodes MUST BE DYNAMIC! for collision to work.

Change texture on SKSpriteNode

I have an SKSpriteNode and I want to change the texture on it when the user touches the screen. But cannot work out how to do so.
Creating and adding the head. (Declared in header).
head = [SKSpriteNode spriteNodeWithImageNamed:[NSString stringWithFormat:#"%#",face]];
head.position = CGPointMake(size.width / 2, size.height / 2);
[self addChild:head];
When a touch is detected, the below is run, but I cannot work out how to apply it to the SKSpritenode?!
SKAction* changeFace = [SKAction setTexture:[SKTexture textureWithImageNamed:[NSString stringWithFormat:#"%#",face]]];
[self runAction:changeFace];
I have tried the below also, but it does not seem to work...
head.texture = [SKTexture textureWithImageNamed:[NSString stringWithFormat:#"%#",face]];
Hope somebody is able to point me in the correct direction!
It looks like you are trying to run the action on the scene (or any other object than your sprite.) The second code should work however, but using the SKAction try this instead.
[head runAction:changeFace];
I have it working here, look at the code below:
1 - Create the SKSpriteNode
self.ninja = [SKSpriteNode spriteNodeWithImageNamed:#"ninja1"];
self.ninja.position = CGPointMake(self.ninja.size.width/2, self.frame.size.height/2);
[self addChild:self.ninja];
2 - Change the texture:
self.ninja.texture = [SKTexture textureWithImageNamed:#"ninja2"];
Obs: I change the texture in touchesBegan event, but this should work in any way you want to do.
I also experiencing this one, I was able to change texture but the the texture is stretch.
What is causing this?
Try This
SKAction*animation=[SKAction animateWithTextures:actions timePerFrame:0.1 resize:NO restore:YES];

CGAffineTransformMakeRotation not working well

I have a game where you have "specks" and "connectors".
I make a UIImageView that connects two "specks"… but as you can see (if the picture works), when the specks are almost on top of each other, like on the left, it doesn't work. This is my code… and I was wondering how you would make the rotation more accurate in that sort of situation.
UIImageView *connector = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"RedConnector.png"]];
connector.contentMode = UIViewContentModeScaleToFill;
connector.hidden = NO;
connector.alpha = 1;
connector.frame = CGRectMake(0, 0, [self DistanceBetweenPoints:speck1.center :speck2.center], 7);
connector.center = CGPointMake((speck1.center.x + speck2.center.x)/2, (speck1.center.y + speck2.center.y)/2);
//This is where the prob is:
connector.transform = CGAffineTransformMakeRotation(tanh((speck2.center.y - speck1.center.y)/(speck2.center.x - speck1.center.x)) );
[Connectors addObject:connector];
[self.view addSubview:connector];
"DistanceBetweenPoints" is not the problem. That works fine. Also, I know the center AND the frame is sort of redundant-- I'll work that out later. Third of all, I have made sure that two specks are never directly on top of each other (to never divide by zero). Last of all, I STILL WANT THESE TO BE UIIMAGEVIEWS!! So I can change the image and animate them so it looks like electricity flowing from speck to speck.
If anybody could show me how to make the rotation more accurate, it would be greatly appreciated. Thanks!
You should use atan2(y,x), not tanh(y/x). That is, you want the arctangent, not the hyperbolic tangent.

How to flip a UIView around the x-axis while simultaneously switching subviews

This question has been asked before but in a slightly different way and I was unable to get any of the answers to work the way I wanted, so I am hoping somebody with great Core Animation skills can help me out.
I have a set of cards on a table. As the user swipes up or down the set of cards move up and down the table. There are 4 cards visible on the screen at any given time, but only the second card is showing its face. As the user swipes the second card flips back onto its face and the next card (depending on the swipe direction) lands in it's place showing its face.
I have set up my card view class like this:
#interface WLCard : UIView {
UIView *_frontView;
UIView *_backView;
BOOL flipped;
}
And I have tried flipping the card using this piece of code:
- (void) flipCard {
[self.flipTimer invalidate];
if (flipped){
return;
}
id animationsBlock = ^{
self.backView.alpha = 1.0f;
self.frontView.alpha = 0.0f;
[self bringSubviewToFront:self.frontView];
flipped = YES;
CALayer *layer = self.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / 500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, M_PI, 1.0f, 0.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;
};
[UIView animateWithDuration:0.25
delay:0.0
options: UIViewAnimationCurveEaseInOut
animations:animationsBlock
completion:nil];
}
This code works but it has the following problems with it that I can't seem to figure out:
Only half of the card across the x-axis is animated.
Once flipped, the face of the card is upside down and mirrored.
Once I've flipped the card I cannot get the animation to ever run again. In other words, I can run the animation block as many times as I want, but only the first time will animate. The subsequent times I try to animate lead to just a fade in and out between the subviews.
Also, bear in mind that I need to be able to interact with the face of the card. i.e. it has buttons on it.
If anybody has run into these issues it would be great to see your solutions. Even better would be to add a perspective transform to the animation to give it that extra bit of realism.
This turned out to be way simpler than I thought and I didn't have to use any CoreAnimation libraries to achieve the effect. Thanks to #Aaron Hayman for the clue. I used transitionWithView:duration:options:animations:completion
My implementation inside the container view:
[UIView transitionWithView:self
duration:0.2
options:UIViewAnimationOptionTransitionFlipFromBottom
animations: ^{
[self.backView removeFromSuperview];
[self addSubview:self.frontView];
}
completion:NULL];
The trick was the UIViewAnimationOptionTransitionFlipFromBottom option. Incidentally, Apple has this exact bit of code in their documentation. You can also add other animations to the block like resizing and moving.
Ok, this won't be a complete solution but I'll point out some things that might be helpful. I'm not a Core-Animation guru but I have done a few 3D rotations in my program.
First, there is no 'back' to a view. So if you rotate something by M_PI (180 degrees) you're going to be looking at that view as though from the back (which is why it's upside down/mirrored).
I'm not sure what you mean by:
Only half of the card across the x-axis is animated.
But, it it might help to consider your anchor point (the point at which the rotation occurs). It's usually in the center, but often you need it to be otherwise. Note that anchor points are expressed as a proportion (percentage / 100)...so the values are 0 - 1.0f. You only need to set it once (unless you need it to change). Here's how you access the anchor point:
layer.anchorPoint = CGPointMake(0.5f, 0.5f) //This is center
The reason the animation only ever runs once is because transforms are absolute, not cumulative. Consider that you're always starting with the identity transform and then modifying that, and it'll make sense...but basically, no animation occurs because there's nothing to animate the second time (the view is already in the state you're requesting it to be in).
If you're animating from one view to another (and you can't use [UIView transitionWithView:duration:options:animations:completion:];) you'l have to use a two-stage animation. In the first stage of the animation, for the 'card' that is being flipped to backside, you'll rotate the view-to-disappear 'up/down/whatever' to M_PI_2 (at which point it will be 'gone', or not visible, because of it's rotation). And in the second stage, you're rotate the backside-of-view-to-disappear to 0 (which should be the identity transform...aka, the view's normal state). In addition, you'll have to do the exact opposite for the 'card' that is appearing (to frontside). You can do this by implementing another [UIView animateWithDuration:...] in the completion block of the first one. I'll warn you though, doing this can get a little bit complicated. Especially since you're wanting views to have a 'backside', which will basically require animating 4 views (the view-to-disappear, the view-to-appear, backside-of-view-to-disappear, and the backside-of-view-to-appear). Finally, in the completion block of the second animation you can do some cleanup (reset view that are rotated and make their alpha 0.0f, etc...).
I know this is complicated, so you might want read some tutorial on Core-Animation.
#Aaron has some good info that you should read.
The simplest solution is to use a CATransformLayer that will allow you to place other CALayer's inside and maintain their 3D hierarchy.
For example to create a "Card" that has a front and back you could do something like this:
CATransformLayer *cardContainer = [CATransformLayer layer];
cardContainer.frame = // some frame;
CALayer *cardFront = [CALayer layer];
cardFront.frame = cardContainer.bounds;
cardFront.zPosition = 2; // Higher than the zPosition of the back of the card
cardFront.contents = (id)[UIImage imageNamed:#"cardFront"].CGImage;
[cardContainer addSublayer:cardFront];
CALayer *cardBack = [CALayer layer];
cardBack.frame = cardContainer.bounds;
cardBack.zPosition = 1;
cardBack.contents = (id)[UIImage imageNamed:#"cardBack"].CGImage; // You may need to mirror this image
[cardContainer addSublayer:cardBack];
With this you can now apply your transform to cardContainer and have a flipping card.
#Paul.s
I followed your approach with card container but when i applt the rotation animation on card container only one half of the first card rotates around itself and finally the whole view appears.Each time one side is missing in the animation
Based on Paul.s this is updated for Swift 3 and will flip a card diagonally:
func createLayers(){
transformationLayer = CATransformLayer(layer: CALayer())
transformationLayer.frame = CGRect(x: 15, y: 100, width: view.frame.width - 30, height: view.frame.width - 30)
let black = CALayer()
black.zPosition = 2
black.frame = transformationLayer.bounds
black.backgroundColor = UIColor.black.cgColor
transformationLayer.addSublayer(black)
let blue = CALayer()
blue.frame = transformationLayer.bounds
blue.zPosition = 1
blue.backgroundColor = UIColor.blue.cgColor
transformationLayer.addSublayer(blue)
let tgr = UITapGestureRecognizer(target: self, action: #selector(recTap))
view.addGestureRecognizer(tgr)
view.layer.addSublayer(transformationLayer)
}
Animate a full 360 but since the layers have different zPositions the different 'sides' of the layers will show
func recTap(){
let animation = CABasicAnimation(keyPath: "transform")
animation.delegate = self
animation.duration = 2.0
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
animation.toValue = NSValue(caTransform3D: CATransform3DMakeRotation(CGFloat(Float.pi), 1, -1, 0))
transformationLayer.add(animation, forKey: "arbitrarykey")
}