我如何才能使障碍物根据玩家移动的距离而产生? [英] How can I make it so that obstacles spawn based on how far the player has moved?

查看:58
本文介绍了我如何才能使障碍物根据玩家移动的距离而产生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成障碍物时遇到问题.我的角色是无限加速的火箭,如果障碍物以固定的速度生成,则火箭将超过障碍物生成的速度.我不想一次生成许多对象.火箭沿对角线运动,因此我编写了一段代码,该代码表明,如果火箭的x位置是5的倍数,它将产生障碍.但是,它永远不会达到5的倍数,因为它的x位置有小数位.

I have a problem when spawning obstacles. My character is a rocket which accelerates indefinitely and if the obstacles spawn at a fixed rate, the rocket will surpass the rate of the obstacles spawning. I do not want to spawn many objects at once. The rocket moves diagonally so I made some piece of code which shows that if the rocket's x position is a multiple of five it would spawn an obstacle. However it never gets to a multiple of five because it's x position has decimals.

到目前为止,这是我的代码.

This is my code so far.

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

public class TriangleSpawner : MonoBehaviour
{
    public GameObject Triangles;
    public float Spacing = 4f;
    Vector2 location;

    void Update()
    {
        location = new Vector2(transform.position.x, transform.position.y);
        if (location.x % 5 == 0)
        {
            Spacing = Spacing + 6.5f;
            GameObject newTriangle = Instantiate(Triangles);
            newTriangle.transform.position = transform.position + new Vector3(Spacing, Random.Range(-4, 3), 0);
        }
    }
}

如何更改此代码,以便它可以根据火箭的位置生成,从而使其永远不会变得太慢?

How can I change this code so it can spawn based on the rocket's position so it never gets too slow?

推荐答案

例如,您可以记住生成对象时的最后位置,然后在每个帧上查看播放器是否已移动得离它足够远以生成另一个对象一. 示例:

You can for example remember the last position when an object was spawned, then see on each frame whether or not the player has moved far enough from it to spawn another one. Example:

private float lastSpawnX;

void Start()
{
    lastSpawnX = transform.position.x;
}

void Update()
{
    if (Mathf.Abs(transform.position.x - lastSpawnX) >= 5)
    {
        lastSpawnX = transform.position.x;
        // Spawn here, do what you have to
    }
}

您还应该考虑当游戏变得太快时,即打算在一帧中移动5个以上的单元时打算做的事情.通常,您总是希望可以达到一定的速度上限.

You should also consider what you are planning to do when the game becomes too fast, i.e you move more than 5 units in one frame. Normally you would always want some upper limit on how fast it can be.

这篇关于我如何才能使障碍物根据玩家移动的距离而产生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆