跟着老鼠

时间:2018-03-20 14:04:25

标签: c# unity3d

我有一个小问题。我有一个跟随鼠标的对象。问题是我想当鼠标离开相机时,对象不再跟随。

  private Vector3 _target;
public Camera Camera;
public bool FollowMouse;
public bool ShipAccelerates;
public float ShipSpeed = 2.0f;
public float offset = 0.0f;


public void OnEnable()
{
    if (Camera == null)
        throw new InvalidOperationException("Camera not set");
}

public void Update()
{
    if (FollowMouse || Input.GetMouseButton(0))
    {
        _target = Camera.ScreenToWorldPoint(Input.mousePosition);
        _target.z = 0;
    }
    Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    difference.Normalize();
    float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(0f, 0f, rotation_z + offset);
    var delta = ShipSpeed * Time.deltaTime;
    if (ShipAccelerates)
        delta *= Vector3.Distance(transform.position, _target);
    transform.position = Vector3.MoveTowards(transform.position, _target, delta);
 if (Bounds)
    {
        transform.position = new Vector3(Mathf.Clamp(transform.position.x, Min_X, Max_X),
                                         Mathf.Clamp(transform.position.y, Min_y, Max_Y));
    }
}

1 个答案:

答案 0 :(得分:0)

在执行MoveTowards之前,只需检查鼠标的位置:

if(Input.mousePosition.x < YourValueHere || Input.mousePosition.x > YourMinValue || Input.mousePosition.y < YourYValue || Input.mousePosition.y > YMinValue)
{
   transform.position = Vector3.MoveTowards(transform.position, _target, delta);
}

如果您希望它与分辨率无关,那么我会使用Screen.HeightScreen.Width的组合作为正值。 0将始终是您的最小值。