我正在尝试编写一个小型游戏,其中游戏对象正在向前运行,直到它针对一个对象运行。当他与物体碰撞时,他向上移动。在一个特定的位置,我希望他再次前进。我试图请求类似的东西:
if(posx == gameObject.transform.position.x && posy == gameObject.transform.position.y)
{
setdirection1();
update();
}
这是我目前的代码:
using UnityEngine;
public class MoveScript : MonoBehaviour
{
// 1 - Designer variables
/// <summary>
/// Object speed
/// </summary>
public Vector2 speed = new Vector2(10, 10);
public string tag = "Seil";
/// <summary>
/// Moving direction
/// </summary>
public Vector2 direction = new Vector2(1, 0);
private Vector2 movement;
void Update()
{
// 2 - Movement
movement = new Vector2(
speed.x * direction.x,
speed.y * direction.y);
}
void setdirection()
{
Vector2 direction1 = new Vector2(0, 1);
direction = direction1;
}
void setdirection1()
{
Vector2 direction2 = new Vector2(1, 0);
direction = direction2;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == tag)
{
setdirection();
Update();
}
}
void FixedUpdate()
{
// Apply movement to the rigidbody
rigidbody.velocity = movement;
}
}
答案 0 :(得分:0)
You should never compare two floats with equality.
Unity特别为此Mathf.Approximately:
if (Mathf.Approximately(posx, gameObject.transform.position.x) && Mathf.Approximately(posy, gameObject.transform.position.y))
{
setdirection1();
update();
}
另外,根据Unity's documentation对于 Vector == Vector (强调我的):
如果向量相等,则返回true 对于非常接近等于的矢量,也会返回true。
因此,您可以这样做:
if (new Vector(posx, posy) == gameObject.transform.position))
{
setdirection1();
update();
}
在我看来,最安全的方法是设置阈值(听起来你有类似的东西):
if (gameObject.transform.position.x < posx ...)
或
if (gameObject.transform.position.x > posx ...)