- Home /
Answer by TheFish657 · Jul 01, 2016 at 04:32 PM
you need to raycast from the camera to the mouse, then add a check for mouse click in an if statement. Then, change the object's x position to the x position of the hit.
Is this also true for 2D games?
EDIT: I mean, I am able to get the mouse position. However, is it necessary to draw a raycast from the camera to the mouse position? I currently notice the mouse position having x and y values disproportionately greater than the actual position.
Vector2 mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
What I was also asking, is it necessary to draw a raycast from the camera to the mouse position? I currently notice the mouse position having x and y values disproportionately greater than the actual position.
Answer by kamyflex · Nov 05, 2016 at 09:03 AM
Use raycast to find where the user clicked, Then create a new Vector3 where "x = raycast.hit.x" and keep y and z the same as your characters y and z, Then use NavMesh to move the object to the Vector3 you created.
Answer by bubzy · Nov 05, 2016 at 07:23 AM
from : https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
using UnityEngine;
public class ExampleClass : MonoBehaviour
{
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
Debug.DrawLine(ray.origin, hit.point);
}
}
you can use the parameters on hit.point
to determine your position to move to
Just to elaborate on your specific request i knocked this up. using UnityEngine; using System.Collections;
public class movetomouse : $$anonymous$$onoBehaviour {
// Use this for initialization
public GameObject objectTo$$anonymous$$ove;
void Start () {
}
// Update is called once per frame
void Update()
{
if (Input.Get$$anonymous$$ouseButtonDown(1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
Debug.DrawLine(ray.origin, hit.point);
objectTo$$anonymous$$ove.transform.position = new Vector3(hit.point.x, objectTo$$anonymous$$ove.transform.position.y, objectTo$$anonymous$$ove.transform.position.z);
}
}
}
Your answer
Follow this Question
Related Questions
OnMouseUp() Click Display Effect. 1 Answer
Mouse Click and Spawn object 4 Answers
How to make object clickable when user enter collider ? 0 Answers
How to properly set the position clicked by the mouse? 0 Answers
Move while mouse button is held down 3 Answers