简体   繁体   English

Unity对象未跟随鼠标位置

[英]Unity object not following mouse position

I have created a object and it is attached to a spring joint 2D and then I have created a script on it so it follows the mouse position. 我创建了一个对象,并将其附加到弹簧接头2D上,然后在其上创建了一个脚本,以便它跟随鼠标的位置。 But it is not happening so and in fact weird thing happens. 但事实并非如此,实际上发生了奇怪的事情。 When I click on object it appears at centre of the screen. 当我单击对象时,它出现在屏幕中央。 Please have a look at my code. 请看一下我的代码。 And why cant I use transform.position with it. 为什么我不能使用transform.position呢? Even more weird things happen. 更奇怪的事情发生了。 Object has a collider and rigidbody2d attached to it 对象具有对撞机和与之碰撞的刚体2d

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

public class Pulling : MonoBehaviour {

    private Rigidbody2D rigidbody;
    private bool ispressed = false;

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

    void Update(){

        if (ispressed) {
            rigidbody.position = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        }
    }

    void OnMouseDown(){
        ispressed = true;
        rigidbody.isKinematic = true;
    }

    void OnMouseUp(){
        ispressed = false;
        rigidbody.isKinematic = false;
    }
}

The problem is that when you use Input.mousePosition as the screen point, its world point will be on the camera in z axis instead of on a further plane with a higher z. 问题是,当您使用Input.mousePosition作为屏幕点时,其世界点将位于相机的z轴上,而不是位于具有更高z的另一平面上。

You can solve this by assigning the z value of the screen point manually. 您可以通过手动指定屏幕点的z值来解决此问题。

rigidbody.position = Camera.main.ScreenToWorldPoint (new Vector3(Input.mousePosition.x, Input.mousePosition.y, z));

where z is the distance of camera from the desired plane. 其中z是相机与所需平面的距离。 (naturally z = -Camera.main.z) (自然地z = -Camera.main.z)

Note that if the camera is aligned with z axis this will work, but if it's angled then ScreenToWorldPoint is not suitable and you need to find another workaround. 请注意,如果摄像机与z轴对齐,则可以使用,但是如果倾斜,则ScreenToWorldPoint不适合,您需要找到其他解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM