对象跟随鼠标拖动Unity 3D

时间:2019-01-09 17:41:01

标签: c# unity3d

我有一个不断向前移动的对象,我想通过鼠标拖动屏幕的任何部分(滑动)使其在X轴上移动,因此我尝试了此代码,但是当第一次单击屏幕时,该对象移动到了鼠标X位置(不拖动)!您对如何使其仅在拖动时移动有任何建议吗?

脚本:

private bool dragging = false;
private float distance;

public Rigidbody Ball;
public float Speed = 100;


// Use this for initialization
void Start () {

}

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

    Ball.velocity = transform.forward * Speed * Time.deltaTime;
}


void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        distance = Vector3.Distance(transform.position, Camera.main.transform.position);
        dragging = true;
    }

    if(Input.GetMouseButtonUp(0))
    {
        dragging = false;
    }

    if (dragging)
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Vector3 rayPoint = ray.GetPoint(distance);
        transform.position = new Vector3(rayPoint.x, transform.position.y, transform.position.z);
    }
}

1 个答案:

答案 0 :(得分:0)

对于继续运动,您可以使用auto-message = !git commit -em "$(git rev-parse --abbrev-ref HEAD | sed 's|.*/||; s|_.*$||;')" (在按钮保持按下状态下为真)(与GetMouseButton相反,只有在按下按钮的第一帧时为真)

您说脚本与GetMouseButtonDown组件相同。在这种情况下,切勿使用

放置对象
RigiBody

但是使用RigidBody.MovePosition之类的

transform.position = ...

最后将鼠标放在初始位置,然后将其用作参考点:

Ball.MovePosition(new Vector3( ... ));

还请注意,我不确定

Vector3 initialPosition;

void Update()
{
    // called the first time mouse button is pressed
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        initialPosition = transform.position;

        Vector3 rayPoint = ray.GetPoint(0);

        // Not sure but this might get you a slightly better value for distance
        distance = Vector3.Distance(transform.position, rayPoint );
    }

    // called while button stays pressed
    if (Input.GetMouseButton(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Vector3 rayPoint = ray.GetPoint(distance);
        Ball.MovePosition(initialPosition + new Vector3(rayPoint.x, 0, 0));
    }
}

是您想要做的。在我看来,// Update is called once per frame void FixedUpdate () { Ball.velocity = transform.forward * Speed * Time.deltaTime; } 的使用在这里没有多大意义。您要么要将速度设置为某个速度,例如

Time.deltaTime

或者您想使用Ball.velocity = transform.forward * Speed; 更改位置,以使运动平稳,如

Time.deltaTime