简体   繁体   中英

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. 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. Even more weird things happen. Object has a collider and rigidbody2d attached to it

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.

You can solve this by assigning the z value of the screen point manually.

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. (naturally 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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