[英]Make a player move towards the direction he is facing (Unity3D/C#)
現在,我在屏幕上有一個小兵,他隨W,A,S,D一起移動,並使用箭頭鍵旋轉/改變方向。 我想發生的是,當玩家的方向發生變化(通過使用箭頭鍵)時,按W會將其發送到該方向,而不是向上移動屏幕。
同樣(例如),如果您同時按住D鍵和向右箭頭鍵,則他應該繞着地面上的一個點繞圈移動(而不是沿直線向右移動時繞圈旋轉)。
這是我當前的代碼:
public class MovePlayer : MonoBehaviour {
void Update() {
// Rotate left
if (Input.GetKey (KeyCode.LeftArrow)) {
transform.Rotate(0, 0, 1.3f);
}
// Rotate right
if (Input.GetKey(KeyCode.RightArrow)) {
transform.Rotate(0, 0, -1.3f);
}
// Strafe left
if (Input.GetKey (KeyCode.A)) {
Vector3 position = this.transform.position;
position.x -= 0.055f;
this.transform.position = position;
}
// Move up
if (Input.GetKey (KeyCode.W)) {
Vector3 position = this.transform.position;
position.y += 0.043f;
this.transform.position = position;
}
// Move down
if (Input.GetKey (KeyCode.S)) {
Vector3 position = this.transform.position;
position.y -= 0.043f;
this.transform.position = position;
isMoving = true;
}
// Strafe right
if (Input.GetKey (KeyCode.D)) {
Vector3 position = this.transform.position;
position.x += 0.055f;
this.transform.position = position;
}
}
}
有任何想法嗎? 不確定要搜索什么。
這是我為角色完成的操作(加上指示腳本的鼠標腳本)
update()
{
Vector3 dir = new Vector3(); //(0,0,0)
//float CharacterSpeed = 10.0f;
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
dir.z += 1.0f;
else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
dir.x -= 1.0f;
else if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
dir.z -= 1.0f;
else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
dir.x += 1.0f;
dir.Normalize();
transform.Translate(dir * CharacterSpeed * Time.deltaTime);
}
如果您只有用於移動的鍵盤:(我不確定%100可以使用此鍵盤)
Vector3 dir = new Vector3(); //(0,0,0)
//float CharacterSpeed = 10.0f;
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
dir.z += 1.0f;
else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
var Rotation = Quaternion.AngleAxis("Rotation Angle Here", transform.InverseTransformDirection(Vector3.up));
transform.localRotation *= Rotation;
}
else if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
dir.z -= 1.0f;
else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
var Rotation = Quaternion.AngleAxis("Rotation Angle Here", transform.InverseTransformDirection(Vector3.up));
transform.localRotation *= Rotation;
}
dir.Normalize();
transform.Translate(dir * CharacterSpeed * Time.deltaTime);
您可以使用Transform.forward
來獲取世界空間中的朝向 ,然后簡單地縮放並加到當前position
。 只需將其連接到W :
this.transform.position += this.transform.forward * 0.043f;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.