Hello, I am relatively new to Unity. I am trying to create a script to attach to a gameobject that will become a cursor for a game I am making. Here is my current script.
using UnityEngine;
using System.Collections;
public class Aim : MonoBehaviour {
Vector3 position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
position.z = 0;
void Start(){
}
void Update(){
transform.position = position;
}
}
Currently it does not work. Is there a way to fix this?
using UnityEngine;
public class Aim : MonoBehaviour {
void Update()
{
//The last bit is important. You need to offset the position from the cameras origin, in some way,
//otherwise the resulting worldPoint will always be 0,0,0
Vector3 screenPoint = Input.mousePosition + Vector3.forward * 10f;
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPoint);
//Notice that I'm not caching the variable or declaring it in the class. You COULD do this,
//but since you need to recalculate it every frame anyway, I see no point.
//The main thing that was wrong with your original script is that you only calculated
//the screen point once, and you did it IN the declaration, which I would have expected to
//throw a thread error.
transform.position = worldPoint;
}
}