为SKScene添加边界 [英] Add boundaries to an SKScene

查看:57
本文介绍了为SKScene添加边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Apple的Sprite Kit框架编写基本的游戏.到目前为止,我已经使用SKPhysicsBody在屏幕上飞行.我想防止飞船从屏幕上飞过,所以我编辑了更新方法以使飞船的速度为零.在大多数情况下,这是可行的,但是时不时地,飞船会从屏幕上飞出.

I'm trying to write a basic game using Apple's Sprite Kit framework. So far, I have a ship flying around the screen, using SKPhysicsBody. I want to keep the ship from flying off the screen, so I edited my update method to make the ship's velocity zero. This works most of the time, but every now and then, the ship will fly off the screen.

这是我的更新方法.

// const int X_MIN = 60;
// const int X_MAX = 853;
// const int Y_MAX = 660;
// const int Y_MIN = 60;
// const float SHIP_SPEED = 50.0;

- (void)update:(CFTimeInterval)currentTime {
    if (self.keysPressed & DOWN_ARROW_PRESSED) {
        if (self.ship.position.y > Y_MIN) {
            [self.ship.physicsBody applyForce:CGVectorMake(0, -SHIP_SPEED)];
        } else {
            self.ship.physicsBody.velocity = CGVectorMake(self.ship.physicsBody.velocity.dx, 0);
        }
    }

    if (self.keysPressed & UP_ARROW_PRESSED) {
        if (self.ship.position.y < Y_MAX) {
            [self.ship.physicsBody applyForce:CGVectorMake(0, SHIP_SPEED)];
        } else {
            self.ship.physicsBody.velocity = CGVectorMake(self.ship.physicsBody.velocity.dx, 0);
        }
    }

    if (self.keysPressed & RIGHT_ARROW_PRESSED) {
        if (self.ship.position.x < X_MAX) {
            [self.ship.physicsBody applyForce:CGVectorMake(SHIP_SPEED, 0)];
        } else {
            self.ship.physicsBody.velocity = CGVectorMake(0, self.ship.physicsBody.velocity.dy);
        }
    }

    if (self.keysPressed & LEFT_ARROW_PRESSED) {
        if (self.ship.position.x > X_MIN) {
            [self.ship.physicsBody applyForce:CGVectorMake(-SHIP_SPEED, 0)];
        } else {
            self.ship.physicsBody.velocity = CGVectorMake(0, self.ship.physicsBody.velocity.dy);
        }
    }
}

起初,我在 didBeginContact 中使用了 applyImpulse 来将飞船推回原处.这使船弹起,但我不希望船弹起.我只想让它停在边缘.

At first, I used applyImpulse in didBeginContact to push the ship back. This made the ship bounce, but I don't want the ship to bounce. I just want it to stop at the edge.

什么是使飞船到达边缘时停下来的正确方法?上面的代码在大多数情况下都有效,但有时飞船会从屏幕上弹出.如果需要的话,这是针对OS X而非iOS的.

What is the right way to make the ship stop once it reaches the edge? The code above works most of the time, but every now and then the ship shoots off screen. This is for OS X—not iOS—in case that matters.

推荐答案

查看此链接...这应该在场景边缘周围设置一个障碍.

This should set up a barrier around the edge of your scene.

苹果公司的这个示例项目可能也很有用 https://developer.apple.com/library/mac/samplecode/SpriteKit_Physics_Collisions/Introduction/Intro.html

This example project from Apple might also be useful https://developer.apple.com/library/mac/samplecode/SpriteKit_Physics_Collisions/Introduction/Intro.html

这篇关于为SKScene添加边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆