[英]Change image when touched
我需要一幅图像来改变自己。
目前,更改的图像是下一个生成的图像,而不是自身。
@implementation MyScene2
{
Marsugo *marsugo;
SKAction *actionMoveDown;
SKAction *actionMoveEnded;
SKTexture *rescued;
}
-(id)initWithSize:(CGSize)size
{
if (self = [super initWithSize:size]) {
// Initializes Background
self.currentBackground = [Background generateNewBackground];
[self addChild:self.currentBackground];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *touch in touches) {
NSArray *nodes = [self nodesAtPoint:[touch locationInNode:self]];
for (SKNode *node in nodes) {
if ([node.name isEqualToString:playerObject]) {
rescued = [SKTexture textureWithImageNamed:@"rescued"];
marsugo.texture = rescued;
// this is changing the image of the next marsugo that spawns instead of self.
}
}
}
}
-(void)addMarsugos
{
// the marsugo is being initialized inside this method, that might be the issue i believe
// Create sprite
marsugo = [[Marsugo alloc]init];
marsugo.xScale = 0.3;
marsugo.yScale = 0.3;
marsugo.zPosition = 75;
// Bounds + Spawn Positions
int minX = marsugo.size.width;
int maxX = self.frame.size.width - marsugo.size.width;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX) + minX;
marsugo.position = CGPointMake(actualX, self.frame.size.height + 50);
[self addChild:marsugo];
// Spawn Timer
int minDuration = 1;
int maxDuration = 10;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;
// Movement Actions
actionMoveDown = [SKAction moveTo:CGPointMake(actualX, CGRectGetMinY(self.frame)) duration:actualDuration];
actionMoveEnded = [SKAction removeFromParent];
[marsugo runAction:[SKAction sequence:@[actionMoveDown, actionMoveEnded]]];
NSLog(@"Marsugo X: %f - Speed: %i", marsugo.position.x, actualDuration);
}
@end
就像我之前说的,我需要使用自定义精灵来更改纹理,而不是“下一个生成精灵”。
修复此问题的任何帮助将不胜感激,谢谢。
您不想使用touchesBegan-最好使用点击手势识别器。 在下面,我有_testView,这是我创建的实例变量,并将其添加到viewDidLoad中的视图中。 然后,我创建了一个轻击手势识别器,该轻击手势识别器会在点击视图时调用一个函数,并且该函数会更改视图的颜色-但在您这种情况下,您可以调用更改图像的函数:
- (void)viewDidLoad {
[super viewDidLoad];
// create the test view and add it as a subview
_testView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 100, 100)];
_testView.backgroundColor = [UIColor redColor];
[self.view addSubview:_testView];
// create the tap gesture recognizer and add it to the test view
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeColor)];
[_testView addGestureRecognizer:tapGestureRecognizer];
}
- (void)changeColor {
// here I'm changing the color, but you can do whatever you need once the tap is recognized
_testView.backgroundColor = [UIColor blueColor];
}
首先导致以下结果:
然后,当我点击视图时:
您可以在Marsugo
类中重写-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
并在那里更改纹理。 这样,您就不必检查触摸是否在您的节点内部,因为如果不是,则不会调用该方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.