首页 > 解决方案 > 我无法随着时间的推移(每秒)提高预制件的速度(Unity)

问题描述

浮动会随着时间的推移而增加,但它不会保持在下一个产生的那个上,所以前 Meteor 1 = -2.5 速度,当它被摧毁,然后 Meteor 2 = -2.5,当它产生时,但我的游戏让它们都在 -2 产生速度 这是移动器本身的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MeteorMover : MonoBehaviour
{
    public float speed = -2f;
    
    
    Rigidbody2D rigidBody;

    // Start is called before the first frame update
    IEnumerator Start()
    {
        
        rigidBody = GetComponent<Rigidbody2D>();
        // Give meteor an initial downward velocity 
        rigidBody.velocity = new Vector2(0, speed);
        

        WaitForSeconds wait = new WaitForSeconds(1);
        int time = 1;
        while (time > 0)
        {
            speed -= .1f;
            time++;
           //yield return speed;
            yield return wait;
        }
        //yield return speed;
        yield return wait;
    }   
}

然后是 spawners 脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MeteorSpawn : MonoBehaviour
{
    public GameObject meteorPrefab;
    public float minSpawnDelay = 1f;
    public float maxSpawnDelay = 3f;
    public float spawnXLimit = 6f;

    // Start is called before the first frame update
    void Start()
    {
        Spawn();
    }

    void Spawn()
    {
        // Create a meteor at a random x position
        float random = Random.Range(-spawnXLimit, spawnXLimit);
        Vector3 spawnPos = transform.position + new Vector3(random, 0f, 0f);
        Instantiate(meteorPrefab, spawnPos, Quaternion.identity);
        
        Invoke("Spawn", Random.Range(minSpawnDelay, maxSpawnDelay));
    }
}

标签: c#unity3d

解决方案


问题是因为您的 MeteorMover 中有以下内容:

public float speed = -2f;

因此,一旦创建了预制件,它的速度就会设置为 -2f。您需要在最后一颗流星被摧毁时获取它的速度,并将该速度用于您实例化的下一个流星。


推荐阅读