![](/img/trans.png)
[英]How can I make 2d object constantly moving in one direction, but when given horizontal input change direction but not change speed?
[英]How can I change the speed of objects that are spawning in constantly in my game?
我正在為 class 編輯一個太空射擊游戲,我正在嘗試創建一個“困難模式”,當玩家按下“e”鍵時,它會加速小行星。 目前使用我的代碼,按下該鍵將加速當前屏幕上的每顆小行星,但新生成的小行星以正常速度運行。 我不知道如何解決,並希望得到一些建議。 這是我的代碼:
public float speed;
private Rigidbody rb;
Vector3 initialForwardVector;
void Start()
{
rb = GetComponent<Rigidbody>();
initialForwardVector = transform.forward;
rb.velocity = initialForwardVector * speed;
}
void Update()
{
if (Input.GetKey (KeyCode.E))
{
rb.velocity = initialForwardVector * (2*speed);
}
}
最快最簡單的解決方案:
public float speed;
public static float speedModifier = 1f;
private Rigidbody rb;
Vector3 initialForwardVector;
void Start()
{
rb = GetComponent<Rigidbody>();
initialForwardVector = transform.forward;
rb.velocity = initialForwardVector * speed * speedModifier;
}
void Update()
{
if (Input.GetKey(KeyCode.E))
{
speedModifier = 2f;
rb.velocity = initialForwardVector * (speedModifier * speed);
}
}
速度修改器將應用於所有新射彈,因為該值在 class 的所有實例之間共享(靜態)。 為了更強大的實現,我建議添加一個 Initialize function ,它將為新的小行星設置一個本地速度修改器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.