我创建了一个按钮类,它有一个 SKSpriteNode 属性、一个 CGRect 属性和一个 Radius 属性(用于圆形按钮)。当您使用图像初始化按钮时,它会根据图像大小设置它的 CGRect 和 Radius 属性。然后,您可以通过调用返回 CGRect 的 -collisionRect 方法来检查玩家是否在点击按钮,并检查“触摸”位置是否在该矩形内。这样按钮可以四处移动并仍然接收输入。这是代码...
/////////////////////////////////////////////////////////////////////////////////////////// /p>
//
// ZSButton.h
// PEGO
//
// Created by Zion Siton on 07/09/2013.
// Copyright (c) 2013 zillustrator. All rights reserved.
//
#import <SpriteKit/SpriteKit.h>
@interface ZSButton : SKNode {
SKSpriteNode *mySprite;
CGRect myRect;
CGFloat myRadius;
}
@property (nonatomic, strong)SKSpriteNode *mySprite;
@property (nonatomic, assign)CGRect myRect;
@property (nonatomic, assign)CGFloat myRadius;
- (id)initWithTexture:(SKTexture *)texture;
- (BOOL)didRadialCollideWith:(CGPoint)aPoint;
@end
//////////////////////////////////////////////////////////////////////////////////////////////////////
//
// ZSButtonA.m
// PEGO
//
// Created by Zion Siton on 07/09/2013.
// Copyright (c) 2013 zillustrator. All rights reserved.
//
#import "ZSButton.h"
@implementation ZSButton
@synthesize mySprite, myRect, myRadius;
- (id)init {
// Use a default button image
return [self initWithTexture:[SKTexture textureWithImageNamed:@"ButtonDefault.png"]];
}
- (id)initWithTexture:(SKTexture *)texture {
self = [super init];
if (self) {
// Assumes there is a texture
mySprite = [SKSpriteNode spriteNodeWithTexture:texture];
[self addChild:mySprite];
// Assumes the collision area is the size of the texture frame
myRect = [mySprite frame];
// Assumes the texture is square
myRadius = myRect.size.width * 0.5;
}
return self;
}
- (CGRect)myRect {
CGPoint pos = [self position];
CGFloat originX = pos.x - (mySprite.frame.width * 0.5);
CGFloat originY = pos.y - (mySprite.frame.height * 0.5);
CGFloat width = mySprite.frame.width;
CGFloat height = mySprite.frame.height;
myRect = CGRectMake(originX, originY, width, height);
return myRect;
}
- (BOOL)didRadialCollideWith:(CGPoint)aPoint {
// Get the distance between the button centre and the touch
// ZSMath is a class I wrote that mainly performs trigonometric functions
CGFloat distance = [ZSMath distanceFromA:[self position] toB:aPoint];
// Perform a radial collision check
if (distance < [self myRadius]) {
// HIT!!!
return YES;
}
// MISS!!!
return NO;
}
@end
//////////////// 初始化按钮...
// Initialize BACK BUTTON
backButton = [[ZSButton alloc] initWithTexture:
[[ZSGraphicLoader sharedGraphicLoader] frameByName:kBACK_BUTTON]];
[self addChild:backButton];
//////////////// 测试碰撞/用户压力
for (UITouch *touch in touches) {
// Get the user's touch location
CGPoint location = [touch locationInNode:self];
// If the user taps on BACK Button Rectangle
if (CGRectContainsPoint(backButton.myRect, location))
{
// DO A RADIAL CHECK
if ([backButton didRadialCollideWith:location])
{
// DO BACK BUTTON STUFF
}
}
}