I’m trying to get a Gameobject that is found by my RaycastHit2D to follow my mouse while I hold down the left mouse button. The Raycast is hitting the Gameobject because the debug.log pops up. But for some reason the Gameobject isn’t following my mouse. It works fine when directly attaching a script to the Gameobject without using a raycast like the following below.
void LateUpdate ()
{
Vector3 mousePositions = new Vector3(transform.position.x + Input.mousePosition.x/sensitivity,transform.position.y + Input.mousePosition.y/sensitivity,transform.position.z);
if (Input.GetMouseButtonDown (0)){
Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
transform.position = Vector3.Lerp(transform.position, mousePositions, Time.smoothDeltaTime/sensitivity);
}
}
So I’m not entirely sure what’s wrong with my current script. It’s an exact copy of the above same but with some raycasting modifications. I tried hit.collider.Gameobject instead of just hit but that didn’t seem to make a difference.
void LateUpdate () {
Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(pos, transform.position);
Debug.DrawLine(Vector2.zero, pos, Color.cyan);
if (hit.collider != null) {
if(Input.GetMouseButtonDown (0)){
Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
Vector3 mousePositions = new Vector3(hit.transform.position.x + Input.mousePosition.x/sensitivity,hit.transform.position.y + Input.mousePosition.y/sensitivity,hit.transform.position.z);
hit.transform.position = Vector3.Lerp(hit.transform.position, pos, Time.smoothDeltaTime/sensitivity);
}
}
}