对象不随鼠标指针移动

时间:2015-11-24 17:30:55

标签: c# unity3d

当我单击鼠标按钮时,我有一个2d对象掉落,并且对象沿着x轴移动就好了。但它并没有根据我的鼠标指针的x坐标移动,当我按下鼠标按钮时,它不会将对象放在鼠标指针所在的位置。我想解决这个问题,让对象沿着x轴移动。

代码:

public class Mouse : MonoBehaviour {

    Rigidbody2D body;
    float mousePosInBlocks;

    void Start () {
        body = GetComponent<Rigidbody2D> ();
    }

    void Update () {

        if (Input.GetMouseButtonDown (0)) {

            body.isKinematic = false;

        }

        Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);

        mousePosInBlocks = Input.mousePosition.x / Screen.width * 4;

        //restrict the position not outside
        ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);

        this.transform.position = ballPos;
    }
}

1 个答案:

答案 0 :(得分:2)

要使对象与光标对齐,请使用camera.ScreenToWorldPoint功能,而不是通过Screen.width分割鼠标位置。简单地按屏幕宽度划分是不正确的,因为如果游戏窗口不完全在屏幕角落,屏幕位置也可能有偏移。这里有更多信息:http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

另外,只是一个建议 - 当使用刚体时,不要使用transform.position,而是使用rigidbody.position,它会更有效率。所以代码看起来像这样:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody2D))]
public class Mouse : MonoBehaviour {

    Rigidbody2D body;
    float mousePosInBlocks;

    void Start () {
        body = GetComponent<Rigidbody2D> ();
    }

    void Update () {

        if (Input.GetMouseButtonDown (0)) {

            body.isKinematic = false;

        }

        Vector3 ballPos = new Vector3 (0f, this.transform.position.y, 0f);

        mousePosInBlocks = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;

        //restrict the position not outside
        ballPos.x = Mathf.Clamp (mousePosInBlocks, -2.65f, 2.65f);

        body.position = ballPos;
    }
}