简体   繁体   English

如何更改游戏中不断生成的对象的速度?

[英]How can I change the speed of objects that are spawning in constantly in my game?

I'm editing a Space Shooter game for class and I am trying to create a "Hard Mode" that speeds up the asteroids when the player presses the key "e".我正在为 class 编辑一个太空射击游戏,我正在尝试创建一个“困难模式”,当玩家按下“e”键时,它会加速小行星。 Currently with my code, pressing the key will speed up every asteroid that is currently on the screen but new asteroids spawned in are at regular speed.目前使用我的代码,按下该键将加速当前屏幕上的每颗小行星,但新生成的小行星以正常速度运行。 I have no idea how to fix and would like some suggestions in what to do.我不知道如何解决,并希望得到一些建议。 Here's my code:这是我的代码:

 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);
    }
 }

Quickest simplest solution:最快最简单的解决方案:

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);
    }
}

The speed modifer will apply to all new projectiles since the value is shared(static) between all instances of the class.速度修改器将应用于所有新射弹,因为该值在 class 的所有实例之间共享(静态)。 For a more robust implementation i suggest adding an Initialize function that would set a local speed modifier for new asteroids.为了更强大的实现,我建议添加一个 Initialize function ,它将为新的小行星设置一个本地速度修改器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM