如何在Sprite Kit中禁用在墙上穿行?

时间:2015-10-21 10:27:10

标签: ios sprite-kit

这是我的播放器:

self.player = [SKSpriteNode spriteNodeWithTexture:[self.spriteAtlas textureNamed:@"idle_0"]];
self.player.texture.filteringMode = SKTextureFilteringNearest;
self.player.position = self.map.spawnPoint;
self.player.name = @"Character";
self.player.physicsBody.allowsRotation = NO;
self.player.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.player.texture.size];
self.player.physicsBody.categoryBitMask = CollisionTypePlayer;
self.player.physicsBody.contactTestBitMask = CollisionTypeExit;
self.player.physicsBody.collisionBitMask = CollisionTypeWall;
self.player.zPosition = 100;

这是我的墙:

SKNode *wall = [SKNode node];
wall.name = @"wall";
wall.position = CGPointMake(position.x + size.width * 0.5f - 0.5f * self.tileSize,
                          position.y - size.height * 0.5f + 0.5f * self.tileSize);
wall.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:size];
wall.physicsBody.dynamic = NO;
wall.physicsBody.categoryBitMask = CollisionTypeWall;
wall.physicsBody.contactTestBitMask = CollisionTypePlayer;
wall.physicsBody.collisionBitMask = CollisionTypePlayer;

我想要做的就是搬到拍打地点。在touchesBegan方法中,我使用tapped位置的坐标运行moveTo动作。如果在拍摄位置和角色之间有一堵墙,它就会直接通过。

当我开始接触墙壁时,我尝试停止移动,但这似乎不是正确的解决方案,因为例如路径与玩家本身一样宽,并且该路径被墙壁包围它不能因与墙壁碰撞而走过。

1 个答案:

答案 0 :(得分:0)

您需要停止使用SKAction移动角色。大多数人尝试使用动作来实现他们的整个游戏机制,而动作实际上是用于一次性动画。行动不灵活。一旦你告诉你的角色移动,他就会移动,无论在路上是什么。

尝试在场景中使用更新方法,并将角色速度设置为触摸方向。这里有一些伪代码..我目前没有运行xcode,但你会得到要点。我们这里只讨论左右运动。

var touch: CGPoint?

func touchesBegan(thisTouch){
    touch = thisTouch.location
}

func update(currentTime) {
    if let moveToTouch = touch {
        if moveToTouch.x > player.position.x {
            player.position.x += 1
        }

        else if moveToTouch.x < player.position.x {
            player.position.y -= 1
        }

        // check how far we are from our destination.  if we reached our destination then we stop
        let distance = sqrt(player.position.x * moveToTouch.x + player.position.y * moveToTouch.y)
        if distance < 1.0 {
            moveToTouch = nil
        }
    }
}