简体   繁体   English

Spritekit自上而下转动角色运动

[英]Spritekit top down turning character movement

I'm creating a top down 'racer' game if you will in Spritekit. 如果您要使用Spritekit,我将创建一个自上而下的“赛车”游戏。 However, I'm already stuck in creating the gameplay. 但是,我已经沉迷于创建游戏玩法。 You control a car from a top down view which is always driving at a constant speed. 您可以自上而下控制始终以恒定速度行驶的汽车。 The player can press two buttons to turn the car left or right. 玩家可以按下两个按钮向左或向右转动汽车。 The speed has to remain constant, but the zRotation of the car has to change. 速度必须保持恒定,但是汽车的zRotation必须改变。 Changing the zRotation isn't the problem, but defining the new velocity of the car is. 改变zRotation不是问题,但是定义汽车的新速度是问题。

I'm currently working with Vectors, so say every time the player presses the 'turnLeft' button the zRotation of the car changes with 45 degrees and a constant velocity of 20, the new velocity would be: 我目前正在使用Vectors,所以说玩家每次按下“ turnLeft”按钮时,汽车的zRotation都会改变45度,且恒定速度为20,新的速度为:

    player.physicsBody.velocity = CGVectorMake(14.14, 14.14);

Given by using the sin and cos of 45 degrees and sum of vectors giving the constant speed 20 ( triangle with two 45 degrees angles and one side of 20). 通过使用45度的sin和cos以及矢量的总和得出恒定速度20(两个45度角且一侧为20的三角形)。

However, I have no idea how I should make this variable every time the player holds the turnLeft button, and if I should use actions or the update function. 但是,我不知道每当玩家按住turnLeft按钮以及应该使用动作或更新功能时如何设置此变量。 It should be possible for the player to drive a circle if he chooses to hold the turnLeft button forever. 如果玩家选择永远按住turnLeft按钮,则应该可以打一个圆圈。 Any help is appreciated! 任何帮助表示赞赏! Thanks. 谢谢。

To calculate the components of the velocity you basically need to do what you stated, except use the zRotation of your sprite in place of 45 degrees. 要计算速度的分量,除了使用sprite的zRotation代替45度之外,基本上需要按照说明进行操作。 For example: 例如:

let speed: CGFloat = 20 // The constant speed.

// Work out the components of velocity:
let dx = speed * cos(sprite.zRotation)
let dy = speed * sin(sprite.zRotation)

sprite.physicsBody!.velocity = CGVector(dx: dx, dy: dy)

As an improvement, it would be better to add this code as an initialiser of CGVector , for reusability: 作为改进,最好将以下代码添加为CGVector的初始化CGVector ,以实现可重用性:

extension CGVector {
    init(length: CGFloat, angle: CGFloat) {
        self.dx = length * cos(angle)
        self.dy = length * sin(angle)
    }
}

You can then use this like so: 然后可以这样使用:

sprite.physicsBody!.velocity = CGVector(length: speed, angle: sprite.zRotation)

Hope that answers your question. 希望这能回答你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM