[英]Issues Getting my GameObject to both Move Forward and Jump properly
我遇到了一個問題,即我的gameObject幾乎沒有跳躍。 我認為這與moveDirection
因為當我注釋掉p.velocity = moveDirection
時,跳轉有效。
對於如何解決這個問題,有任何的建議嗎?
using UnityEngine;
using System.Collections;
public class Controller : MonoBehaviour
{
public float jumpHeight = 8f;
public Rigidbody p;
public float speed = 1;
public float runSpeed = 3;
public Vector3 moveDirection = Vector3.zero;
// Use this for initialization
void Start ()
{
p = GetComponent<Rigidbody>();
p.velocity = Vector3.zero;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.Space))
{
p.AddForce(new Vector3(0, jumpHeight, 0), ForceMode.Impulse);
}
Move ();
}
void Move ()
{
if(Input.GetKey(KeyCode.D))
{
transform.Rotate(Vector3.up, Mathf.Clamp(180f * Time.deltaTime, 0f, 360f));
}
if(Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.up, -Mathf.Clamp(180f * Time.deltaTime, 0f, 360f));
}
moveDirection = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
if(Input.GetKey(KeyCode.LeftShift))
{
moveDirection *= runSpeed;
}
else
{
moveDirection *= speed;
}
p.velocity = moveDirection;
}
}
嘗試為您的jumpheight變量使用更高的值。 我通常會帶幾百個東西。
因為在字面上在同一幀內執行AddForce(...)
之后,您立即使用moveDirection
覆蓋了速度。 您應該添加當前速度,而不是像這樣完全覆蓋它:
Vector3 velocity = p.velocity;
p.velocity = velocity + moveDirection;
這就是Unity警告不要直接搞亂速度的原因 ,最好為運動做另一個AddForce(...)
:
p.AddForce(moveDirection * Time.deltaTime);
編輯:
我不喜歡偏離OP的問題太多,但是您的新問題可能是因為您對moveDirection
所做的事情太多了,我什至不明白為什么一半,但大部分情況下看起來應該是這樣的:
moveDirection = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")).normalized;
float _speed = Input.GetKey(KeyCode.LeftShift) ? runspeed : speed;
p.AddForce(moveDirection * _speed * Time.deltaTime);
好吧,我想出了解決方法。 而不是將這些MoveDirection變量更改為
if(Input.GetKey(KeyCode.W)) {
transform.position += transform.forward * Time.deltaTime * speed;
}
if(Input.GetKey(KeyCode.S)) {
transform.position -= transform.forward * Time.deltaTime * speed;
}
現在可以正常工作了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.