我只需要在我按住鍵盤上的 W 鍵時物體移動,一旦我松開鍵,它必須平穩停止。
這是我的代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Car : MonoBehaviour
{
public Rigidbody rb;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.W))
{
rb.AddForce (transform.forward*100*Time.deltaTime);
}
}
}
uj5u.com熱心網友回復:
嘗試使用 GetKey 而不是 GetKeyDown
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Car : MonoBehaviour
{
public Rigidbody rb;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.W))
{
rb.AddForce (transform.forward*100*Time.deltaTime);
}
}
}
uj5u.com熱心網友回復:
你的意思是你想呼叫 rb.AddForce 一次嗎?像這樣修復它,通過添加一個變數 isMoving:
public class Car : MonoBehaviour
{
private bool isMoving;
public Rigidbody rb;
// Start is called before the first frame update
void Start()
{
isMoving = false;
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.W) && !isMoving)
{
rb.AddForce (transform.forward*100*Time.deltaTime);
isMoving = true;
}
}
}
uj5u.com熱心網友回復:
Input.GetKeyDown僅true ONCE在按下按鈕的幀。
這聽起來像你更愿意使用Input.GetKey這是true每幀WHILE按鈕保持按下。
一般來說,雖然你應該施加力量等而不是 FixedUpdate
void FixedUpdate()
{
if(Input.GetKey(KeyCode.W))
{
rb.AddForce(rb.GetRelativeVector(Vector3.forward) * 100 * Time.deltaTime);
}
// If you want it to stop immediately - not very realistic though
// and would require more checks like is it actually on the ground etc
//else
//{
// rb.velocity = Vector3.zero;
//}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/344694.html
上一篇:傳送錯誤Unity2d
