I have got a SKScene name “Scene” in which I instantiate 2 objects of my class “Button” subclass of SKNode.
In order to not multiply the number of lines of code in my SKScene, I wanted to implemente the touch methods directly in my class “Button”.
Here is the code :
Scene.h
#import <SpriteKit/SpriteKit.h>
#interface Scene : SKScene
#end
Scene.m
#import "Scene.h"
#import "Button.h"
#implementation Scene
- (id)initWithSize:(CGSize)size
{
if (self = [super initWithSize:size])
{
Button *button01 = [Button node];
[button01.number setString: #"1"];
button01.position = CGPointMake(CGRectGetMidX(self.frame) - 50, 160);
Button *button02 = [Button node];
[button02.number setString: #"2"];
button02.position = CGPointMake(CGRectGetMidX(self.frame) + 50, 160);
[self addChild:button01];
[self addChild:button02];
}
return self;
}
#end
Button.h
#import <SpriteKit/SpriteKit.h>
#interface Button : SKNode
#property (strong, nonatomic) NSMutableString *number;
#end
Button.m
#import "Button.h"
SKShapeNode *button;
#implementation Button
- (id)init
{
if (self = [super init])
{
self.userInteractionEnabled = YES;
_number = [[NSMutableString alloc] init];
[_number setString: #"0"];
button = [SKShapeNode node];
[button setPath:CGPathCreateWithRoundedRect(CGRectMake(-25, -25, 50, 50), 4, 4, nil)];
button.fillColor = [SKColor clearColor];
button.lineWidth = 1.0;
button.strokeColor = [SKColor whiteColor];
button.position = CGPointMake(0, 0);
SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:#"Arial"];
label.text = _number;
label.fontSize = 20;
label.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;
label.position = CGPointMake(0, 0);
label.fontColor = [SKColor whiteColor];
[button addChild:label];
[self addChild:button];
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
if(CGRectContainsPoint(button.frame, location))
{
button.fillColor = [SKColor whiteColor];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
button.fillColor = [SKColor clearColor];
}
#end
The problem is when I touch inside the button01, it’s the button02 color’s which change. As if the action is only apply on the last instance of my class.
How can I fixe this.
Thanks in advance.
The issue is the following variable has global scope in your Button class:
SKShapeNode *button;
Since it is shared among the instances of Button, it contains a reference to the SKShapeNode of the last Button that was instantiated. In this case, button 2. You can resolve this issue by defining button as an instance variable:
#implementation Button
{
SKShapeNode *button;
}
...
For some reasons your Button has SKNode as a superclass. SKNode doesn't have a size property, which you can change, so it takes the whole size of it's parent node. Consider it as a layer of the scene. So wherever you touch, the latest SKScene's child (which is button02 in your case) will receive the touch.
Solution: Define Button as a subclass of SKShapeNode directly.
Related
I need to make an end screen for my app after the collision detection. What is the easiest possible way to make the end screen with a button back to the main menu/to the game. Can I use a ViewController? I've read a lot of tutorials, videos, and also all of the posts on here:
This is my current code (not all of it just some important things):
#implementation MyScene
static const int squirrelHitCategory = 1;
static const int nutHitCategory = 2;
- (instancetype)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.physicsWorld.contactDelegate = self;
_squirrelSprite = [SKSpriteNode spriteNodeWithImageNamed:#"squirrel"];
_squirrelSprite.position = _firstPosition;
_atFirstPosition = YES;
_squirrelSprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:10];
_squirrelSprite.physicsBody.categoryBitMask = squirrelHitCategory;
_squirrelSprite.physicsBody.contactTestBitMask = nutHitCategory;
_squirrelSprite.physicsBody.collisionBitMask = nutHitCategory;
_squirrelSprite.physicsBody.affectedByGravity = NO;
self.physicsWorld.contactDelegate = self;
[self addChild:_squirrelSprite];
SKAction *wait = [SKAction waitForDuration:3.0];
SKSpriteNode *lightnut = [SKSpriteNode spriteNodeWithImageNamed:#"lightnut.png"];
lightnut.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(200,160)];
lightnut.physicsBody.categoryBitMask = nutHitCategory;
lightnut.physicsBody.contactTestBitMask = squirrelHitCategory;
lightnut.physicsBody.collisionBitMask = squirrelHitCategory;
lightnut.physicsBody.affectedByGravity = NO;
self.physicsWorld.contactDelegate = self;
[self addChild: lightnut];
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
// Check time since the last touch event
if (touch.timestamp-_lastTouch >= .9) {
// Allow touch
NSLog(#"greater than or equal to 3 seconds");
if (_atFirstPosition)
{
SKAction *moveNodeLeft = [SKAction moveByX:-207.8 y:0.0 duration:0.85];
[_squirrelSprite runAction: moveNodeLeft withKey:#"moveleft"];
} else {
SKAction *moveNodeRight = [SKAction moveByX:207.8 y:0.0 duration:0.85];
[_squirrelSprite runAction: moveNodeRight withKey:#"moveright"];
}
_atFirstPosition = !_atFirstPosition;
_squirrelSprite.xScale *= -1.0;
}
else {
// Ignore touch
NSLog(#"Seconds since last touch %g",touch.timestamp-_lastTouch);
}
// Store timestamp
_lastTouch = touch.timestamp;
}
-(void)didBeginContact:(SKPhysicsContact *)contact
{
NSLog(#"contact detected");
SKPhysicsBody *firstBody, *secondBody;
firstBody = contact.bodyA;
secondBody = contact.bodyB;
if(firstBody.categoryBitMask == squirrelHitCategory || secondBody.categoryBitMask == nutHitCategory)
{
}
}
I want my end screen to be simple, so the easiest way to make it is best. Thank you!
For my games I add a UIViewController property and assign it to the SKScene.
You can then add a view as a sub view. Example...
SKScene *scene = [SKScene sceneWithSize:self.view.frame.size];
scene.viewController = self;
Then in your scene...
[self.viewController addSubview:yourView];
Here is some of my own game's implementation to help get you started.
In your Storyboard, or XIB whichever you prefer you add a view with buttons as properties of the view. In my case I have a scoreLabel, a menuButton, and a restartButton as properties and can set them all as x.hidden = YES; as I wish by triggering them in the scene such as...
self.vc.menuButton.hidden = YES;
self.vc.restartButton.hidden = YES;
In your GameViewController (Which is a subclass of UIViewController)...
//header
#interface GameViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *scoreLabel;
#property (weak, nonatomic) IBOutlet UIView *hudView;
#property (weak, nonatomic) IBOutlet UIButton *menuButton;
#property (weak, nonatomic) IBOutlet UIButton *restartButton;
#property (nonatomic) MazeScene *maze;
#end
//class
- (void)viewDidLoad
{
[super viewDidLoad];
// Configure the view.
SKView * skView = (SKView *)self.view;
// Debug Options
// skView.showsFPS = YES;
// skView.showsNodeCount = YES;
// skView.showsPhysics = YES;
// Create and configure the maze scene.
CGSize sceneSize = skView.bounds.size;
skView.ignoresSiblingOrder = YES;
MazeScene *maze = [[MazeScene alloc] initWithSize:sceneSize];
maze.scaleMode = SKSceneScaleModeAspectFill;
maze.vc = self;
[skView presentScene:maze];
_maze = maze;
}
In your SKScene...
//header
#interface MazeScene : SKScene <SKPhysicsContactDelegate>
#property (nonatomic, weak) GameViewController *vc;
#end
//class
-(id) initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
//(GameViewController*) is a static cast of a subclass of UIViewController.
[self.view addSubview:((GameViewController*)self.vc).hudView];
// [self restartGame] is a specific method for my game, don't worry about it
[self restartGame];
}
return self;
}
I want to drag my label in Application. I create new label when starting Application
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
myLabel.text = #"DRAG ME!!!";
[self.view addSubview:myLabel];
How can I drag this label? I can't find normal tutorial and i new in Xcode...
The following implementation may help you. Change your above label with this one and you can see that now your label is draggable.
#import "DraggableLabel.h"
#interface DraggableLabel()
{
CGPoint _previousLocation;
}
#end
#implementation DraggableLabel
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.userInteractionEnabled = YES;
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
action:#selector(handlePan:)];
self.gestureRecognizers = #[panRecognizer];
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.superview bringSubviewToFront:self];
_previousLocation = self.center;
}
- (void)handlePan:(UIPanGestureRecognizer *)panGestureRecognizer
{
CGPoint translation = [panGestureRecognizer translationInView:self.superview];
self.center = CGPointMake(_previousLocation.x + translation.x,
_previousLocation.y + translation.y);
}
#end
// Player.m
#import "Player.h"
#implementation Player
+(id)player{
Player *player = [Player spriteNodeWithColor:[UIColor brownColor] size:CGSizeMake(32, 32)];
player.name = #"player";
player.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:player.size];
return player;
}
- (void)walkRight {
SKAction *incRight = [SKAction moveByX:10 y:0 duration:0];
[self runAction:incRight];
}
#end
// MyScene.h
#import "MyScene.h"
#import "Player.h"
#implementation MyScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */
self.anchorPoint = CGPointMake(0.5, 0.5);
self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
SKSpriteNode *ground = [SKSpriteNode spriteNodeWithColor:[UIColor greenColor] size:CGSizeMake(self.frame.size.width, 30)];
ground.position = CGPointMake(0, -self.frame.size.height/2 + ground.frame.size.height/2);
ground.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ground.size];
ground.physicsBody.dynamic = NO;
[self addChild:ground];
Player *player = [Player player];
[self addChild:player];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
Player *player = (Player *)[self childNodeWithName:#"player"];
[player walkRight];
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
}
#end
I'm quite new to objective-c. Well I tried to build the above code and got the error "no visible #interface for 'Player' declares the selector 'walkRight'"
I really do not know why. I would really appreciate it if someone could help me. Thank you.
Make sure you've declared the walkRight method in your Player.h file. This should go somewhere after your interface declaration in that file:
-(void)walkRight;
That allows other files that import Player.h to know that Player.m implements the walkRight method.
Change your player method to return instancetype instead of id. This will make the warning go away. Also declare the walkRight method in the header (.h) file of your Player class.
+(instancetype)player{
Player *player = [Player spriteNodeWithColor:[UIColor brownColor] size:CGSizeMake(32, 32)];
....
return player;
}
Read more about instancetype here and here.
Hope that helps!
I have two images: first image size is 50x85 and second image size is 50x113. When I touch the screen image goes up and second image is shown and when I release the screen image goes down and first image is shown. Now the problem is when I'm touching the screen collision happens earlier than when I'm not touching the screen.
How could I make that in second image about 30px at bottom won't collide, but image will still be there?
Edit: Here is some of the code:
-(void)AstronautMove
{
[self Collision];
Astronaut.center = CGPointMake(Astronaut.center.x, Astronaut.center.y + Y);
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
Y = -10;
x.image = [UIImage imageNamed:#"y.png"];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
Y = 17;
x.image = [UIImage imageNamed:#"x.png"];
}
-(void)Collision
{
if (CGRectIntersectsRect(Astronaut.frame, Landingarea.frame)) {
[self EndGame];
AstronautFire.hidden = YES;
RedBorder.hidden = NO;
AstronautCrashed.hidden = NO;
}
if (CGRectIntersectsRect(AstronautFire.frame, Landingarea.frame)) {
[self EndGame];
AstronautFire.hidden = YES;
RedBorder.hidden = NO;
AstronautCrashed.hidden = NO;
}
}
I'm just moving the frame up and down. At the bottom is landing area. When Astronaut and landing area frames touch, collision happens. But when I'm moving Astronaut up bigger image is shown (50x113) and when I'm moving Astronaut down smaller image is shown (50x85). When I'm near landing area and I press to go up bigger image shows and collision happens.
From the code samples, it really is hard to follow what you're trying to do. Notably, it's unclear how (or even if) you're animating the moving of the various views.
Whether you're animating or not, it's not clear from your code sample as to where AstronautMove is called. Did you mean to call that from touchesBegan and touchesEnded? But on the basis of what's been shared thus far, I don't see you calling AstronautMove and therefore don't see how you could possibly detect collisions.
Personally, I would have thought that you'd want to animate the moving of the views (it will render a more realistic and engaging moving of the views). And then, while an animation is underway, keep checking for a collision. In terms of how to "keep checking", you can use either a NSTimer or, even better, us a CADisplayLink (a mechanism to call a method each and every time the screen updates).
For example, you could do something like:
#interface ViewController ()
#property (nonatomic, strong) UIView *view1;
#property (nonatomic, strong) UIView *view2;
#property (nonatomic, strong) CADisplayLink *displayLink;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
view1.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:view1];
self.view1 = view1;
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(50, 150, 50, 50)];
view2.backgroundColor = [UIColor darkGrayColor];
[self.view addSubview:view2];
self.view2 = view2;
}
#pragma mark - Handle touches
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self startAnimationTo:CGPointMake(50, 250) collisionChecking:YES];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self startAnimationTo:CGPointMake(50, 50) collisionChecking:NO];
}
#pragma mark - Handle starting and stopping of animation
- (void)startAnimationTo:(CGPoint)point collisionChecking:(BOOL)collisionChecking
{
if (collisionChecking)
[self startDisplayLink];
[UIView animateWithDuration:2.0 delay:0.0 options:0 animations:^{
CGRect frame = self.view1.frame;
frame.origin = point;
self.view1.frame = frame;
} completion:^(BOOL finished) {
// in case we never have collision, let's make sure we stop the display link
if (collisionChecking)
[self stopDisplayLink];
}];
}
- (void)stopAnimation
{
CALayer *layer = self.view1.layer.presentationLayer;
[self.view1.layer removeAllAnimations];
self.view1.frame = layer.frame;
[self stopDisplayLink];
}
#pragma mark - Handle the display link & check for collisions
- (void)startDisplayLink
{
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:#selector(checkForCollision:)];
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)stopDisplayLink
{
[self.displayLink invalidate];
self.displayLink = nil;
}
- (void)checkForCollision:(CADisplayLink *)displayLink
{
// Note, when checking for collision while an animation is underway, the `frame` of the
// view represents the final location of the view, not the current location. To get the
// current location, one has to grab the `presentationLayer`. So, we're going to get the
// `presentationLayer` of each of the views and use those to determine a collision.
CALayer *layer1 = self.view1.layer.presentationLayer;
CALayer *layer2 = self.view2.layer.presentationLayer;
if (CGRectIntersectsRect(layer1.frame, layer2.frame)) {
[self stopAnimation];
}
}
#end
Or, in iOS 7, you can use UIKit Dynamics to animate the movement of the views, identifying collisions programmatically using a UICollisionBehavior and assigning a collisionDelegate:
#interface ViewController () <UICollisionBehaviorDelegate>
#property (nonatomic, strong) UIView *view1;
#property (nonatomic, strong) UIView *view2;
#property (nonatomic, strong) UIDynamicAnimator *animator;
#property (nonatomic, strong) UISnapBehavior *snap;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
view1.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:view1];
self.view1 = view1;
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(50, 150, 50, 50)];
view2.backgroundColor = [UIColor darkGrayColor];
[self.view addSubview:view2];
self.view2 = view2;
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
// create behavior that will detect collisions, calling the `UICollisionBehaviorDelegate`
// methods if and when collisions are detected
UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:#[view1, view2]];
collision.translatesReferenceBoundsIntoBoundary = YES;
collision.collisionDelegate = self;
[self.animator addBehavior:collision];
// in this example, I'm going to fix `view2` where it is, so it doesn't move when
// `view1` collides with it
UIAttachmentBehavior *attachment = [[UIAttachmentBehavior alloc] initWithItem:self.view2 attachedToAnchor:self.view2.center];
[self.animator addBehavior:attachment];
// finally, let's specify that neither view1 nor view2 should rotate when
// snapping, colliding, etc.
UIDynamicItemBehavior *noRotate = [[UIDynamicItemBehavior alloc] initWithItems:#[view1, view2]];
noRotate.allowsRotation = NO;
[self.animator addBehavior:noRotate];
}
- (void)addSnap:(CGPoint)point
{
[self removeSnap];
self.snap = [[UISnapBehavior alloc] initWithItem:self.view1 snapToPoint:point];
[self.animator addBehavior:self.snap];
[self.animator updateItemUsingCurrentState:self.view1];
}
- (void)removeSnap
{
if (self.snap) {
[self.animator removeBehavior:self.snap];
self.snap = nil;
}
}
#pragma mark - Handle touches
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self addSnap:CGPointMake(75, 225)];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self addSnap:CGPointMake(75, 75)];
}
#pragma mark - UICollisionBehaviorDelegate
// you can use these to be informed when there is a collision
- (void)collisionBehavior:(UICollisionBehavior *)behavior beganContactForItem:(id<UIDynamicItem>)item withBoundaryIdentifier:(id<NSCopying>)identifier atPoint:(CGPoint)p
{
NSLog(#"%s", __FUNCTION__);
[self removeSnap];
}
- (void)collisionBehavior:(UICollisionBehavior *)behavior beganContactForItem:(id<UIDynamicItem>)item1 withItem:(id<UIDynamicItem>)item2 atPoint:(CGPoint)p
{
NSLog(#"%s", __FUNCTION__);
[self removeSnap];
}
#end
Or, for a game, SpriteKit might be even better. You can google "SpriteKit example" and you'll probably find plenty of good introductions to SpriteKit.
I know that neither of the above examples are quite what you're doing, but hopefully it illustrates a couple of techniques for identifying collisions, which you could adapt for your app.
I have been trying to implement dragable UIButton in iOS by overriding touchesMoved method.
The button shows up , however i am not able to drag it.What am i missing here?
this is what i reffered
This is my .h file.
#interface ButtonAnimationViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIButton *firstButton;
And the .m file.
#implementation ButtonAnimationViewController
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint pointMoved = [touch locationInView:self.view];
self.firstButton.frame = CGRectMake(pointMoved.x, pointMoved.y, 73, 44);
}
Here you have a fully working button dragging example using UIPanGestureRecognizer which, in my opinion, is easier. I tested it before posting the code. Let me know if you have any more questions:
#interface TSViewController ()
#property (nonatomic, strong) UIButton *firstButton;
#end
#implementation TSViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// this code is just to create and configure the button
self.firstButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.firstButton setTitle:#"Button" forState:UIControlStateNormal];
self.firstButton.frame = CGRectMake(50, 50, 300, 40);
[self.view addSubview:self.firstButton];
// Create the Pan Gesture Recognizer and add it to our button
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(dragging:)];
[self.firstButton addGestureRecognizer:panGesture];
}
// this method will be called whenever the user wants to drag the button
-(void)dragging:(UIPanGestureRecognizer*)panGesture {
// if is not our button, return
if (panGesture.view != self.firstButton) {
return;
}
// if the gesture was 'recognized'...
if (panGesture.state == UIGestureRecognizerStateBegan || panGesture.state == UIGestureRecognizerStateChanged) {
// get the change (delta)
CGPoint delta = [panGesture translationInView:self.view];
CGPoint center = self.firstButton.center;
center.x += delta.x;
center.y += delta.y;
// and move the button
self.firstButton.center = center;
[panGesture setTranslation:CGPointZero inView:self.view];
}
}
#end
Hope it helps!