在 Unity 2D 游戏中精灵以疯狂的速度移动并穿过物体掉落

问题描述 投票:0回答:1

我有一个放置在块(Tilemap)顶部的错误模型。 Tilemap 有一个 Tilemap Collider 组件。当我启动游戏时,虫子移动得很好,但几秒钟后它开始稍微落在地板下,然后以疯狂的速度加速。这是错误的代码:

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Enemy : MonoBehaviour
{

    public float speed = 50f;
    public Vector3[] positions;
    private int indexPosition;

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

    // Update is called once per frame
    void Update()
    {

        if (transform.position.x > GameObject.Find("Player").transform.position.x) {
            GetComponent<SpriteRenderer>().flipX = true; }
        else {
            GetComponent<SpriteRenderer>().flipX = false; }

        transform.position = Vector3.MoveTowards(transform.position, positions[indexPosition], speed/1000);
        

        if (transform.position == positions[indexPosition]) {

            if (indexPosition < positions.Length - 1) {

                indexPosition++;

            }

            else {

                indexPosition = 0;
                

            }

        }
    }

    private void OnCollisionEnter2D(Collision2D other) {
        if (other.gameObject.CompareTag("Player")) {

            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

        }
    }

    private void OnTriggerEnter2D(Collider2D other) {
        if (other.gameObject.CompareTag("Player")) {

            Destroy(gameObject);

        }
    }
}

请注意,我的组件中有 2 个 Vector3 值,它们都是正确的,并且 bug 不应该在地板上出现故障

我尝试询问我的团结老师,但两节课过去了,问题仍然存在

我预计错误会从一个位置移动到另一个位置

unity-game-engine
1个回答
0
投票

听起来你有一个带有重力的刚体。

我猜你的

moveTowards

        if (transform.position == positions[indexPosition]) {

并不总是能实现这种平等。然后重力开始变得大于你的速度。

如果您使用

positions
数组对其位置进行硬编码,则可能不需要重力

© www.soinside.com 2019 - 2024. All rights reserved.