Move an object with onMouseDrag in Unity?

1

This code in theory works to move an object as I have seen in tutorials, but I do not move the sphere and I do not know why. I've assigned the script and everything but nothing ... what's wrong?

public class mouseDrag : MonoBehaviour {

float distance = 10;

void onMouseDrag() {

    Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, distance);
    Vector3 objPosition = Camera.main.ScreenToWorldPoint (mousePosition);

    transform.position = objPosition;

}


// Use this for initialization
void Start () {

}

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

  }
}
    
asked by Rf Mvs 14.03.2017 в 12:05
source

1 answer

1

Your code has a typo error is not onMouseDrag() is OnMouseDrag() or is capitalized:

  float distance = 10;

void onMouseDrag() {

    Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, distance);
    Vector3 objPosition = Camera.main.ScreenToWorldPoint (mousePosition);

    transform.position = objPosition;

}

void OnMouseDrag() {
//..

with the above it should work if it is not so try the next code is more less than yours, but also this has to change the color of the object if it does not work either, I think the error is a matter of Trigger.

//..
public Renderer rend;

void Start () {

    rend = GetComponent<Renderer>();
}

//..
float distance = 10;
Vector3 mousePosition; 

/*El vector esta fuera para que no tenga que 
  ser creado cada ves, no es muy bueno que digamos 
  crear cientos de objetos una y otra ves, si no es 
  necesarios, asi no emplear ese tiempo en crearlos y 
  hacer trabajar de mas al recolector de basura.*/

  //P.D: con el tipo vector no es muy apreciable 
  //(por no entrar en tecnicismos) 
  //hasta cierto punto, pero
  //pienso que es mejor acostumbrase a no crear objetos en lugares que se 
  //llaman "x" veces por frame. 

void OnMouseDrag() {

    mousePosition = Input.mousePosition;
    mousePosition.z = distance;
    transform.position = Camera.main.ScreenToWorldPoint (mousePosition);

    rend.material.color -= Color.white * Time.deltaTime;
}
//..
    
answered by 14.03.2017 в 17:31