【问题标题】:Problem with my object that does not stop moving我的物体没有停止移动的问题
【发布时间】:2021-03-07 22:13:05
【问题描述】:

我编写了一个脚本,用于将对象移动到鼠标单击所指示的位置。如果我不选择单击到另一个位置移动,如果它到达前面提到的位置,我想停止我的对象。但是,对象在到达该位置时并没有停止,而是继续移动。 这是我写的代码。如果有人知道如何解决此问题,我将不胜感激。

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

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    private Vector3 targetPos;
    private Rigidbody2D rb;
    private bool isMoving;
    private Vector2 direction;
    public  float changeDirCooldown;

    private float changeCool;
    private bool canChangeDir;
    
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();

        changeCool=changeDirCooldown;
        canChangeDir =true;
    }

  
    void Update()
    {

        if (Input.GetMouseButton(0) && canChangeDir)
        {
            
            changeDirCooldown = changeCool;
            SetTargetPosition();
        }
            
        if (changeDirCooldown<=0)
        {
            canChangeDir = true;
            
       
        }
        
        else
        {
            changeDirCooldown -= Time.deltaTime;
        }
     
    }
    private void FixedUpdate()
    {
        if (isMoving)
        {
            Move();
            
        }
        if (this.transform.position == this.targetPos)
        {
            
            isMoving = false;
            rb.velocity = Vector2.zero;
          
        }
    }

    private void SetTargetPosition()
    {
        targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        targetPos.z = transform.position.z;
        direction = targetPos - this.transform.position;
        direction = direction.normalized;
        isMoving = true;
    }
    private void Move()
    {
        rb.velocity = direction * moveSpeed;
        canChangeDir = false;
    }
}

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    这可能是浮点数容差的问题。这一行

    this.transform.position == this.targetPos
    

    几乎永远不会结果为真,所以你应该这样做:

    Mathf.Abs(this.transform.position.x - this.targetPos.x) < float.Epsilon &&
    Mathf.Abs(this.transform.position.y - this.targetPos.y) < float.Epsilon
    

    【讨论】:

      猜你喜欢
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多