Spritekit自上而下转动角色运动 [英] Spritekit top down turning character movement

查看:165
本文介绍了Spritekit自上而下转动角色运动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您要使用Spritekit,我将创建一款自上而下的赛车"游戏.但是,我已经陷于创建游戏过程中了.您可以自上而下控制始终以恒定速度行驶的汽车.玩家可以按下两个按钮向左或向右转动汽车.速度必须保持恒定,但是汽车的zRotation必须改变.改变zRotation不是问题,但是定义汽车的新速度是问题.

I'm creating a top down 'racer' game if you will in 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. Changing the zRotation isn't the problem, but defining the new velocity of the car is.

我目前正在使用Vectors,所以说玩家每次按下"turnLeft"按钮时,汽车的zRotation都会改变45度,且恒定速度为20,新速度将为:

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:

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

使用45度的正弦和余弦以及矢量和得出恒定速度20(具有两个45度角且一侧为20的三角形)给出.

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).

但是,我不知道每当玩家按住turnLeft按钮时,应该如何设置此变量,以及是否应该使用动作或更新功能.如果玩家选择永远按住turnLeft按钮,则应该可以打圈.任何帮助表示赞赏!谢谢.

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. It should be possible for the player to drive a circle if he chooses to hold the turnLeft button forever. Any help is appreciated! Thanks.

推荐答案

要计算速度的分量,您基本上需要按照您所说的做,除了使用Sprite的zRotation代替45度.例如:

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. 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)

作为改进,为可重用性,最好将此代码添加为CGVector的初始化程序:

As an improvement, it would be better to add this code as an initialiser of CGVector, for reusability:

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)

希望能回答您的问题.

这篇关于Spritekit自上而下转动角色运动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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