fluentparrot fluentparrot - 1 month ago 23
C# Question

make object move to the mouse clicked position 2d

This is the code for 3D in unity. I changed this to the 2D form, but the object does not move in the 2D world. The writer said it will be okay if I change the word from 3D to 2D, but I seem to be missing something.

private bool flag = false;
private Vector2 endPoint;
public float duration = 50.0f;
private float yAxis;

void Start()
{
yAxis = gameObject.transform.position.y;
}

void Update()
{

if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
{
RaycastHit hit;
Ray ray;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out hit))
{
flag = true;
endPoint = hit.point;
endPoint.y = yAxis;
Debug.Log(endPoint);
}

}

if (flag && !Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude))
{
gameObject.transform.position = Vector2.Lerp(gameObject.transform.position, endPoint, 1 / (duration * (Vector2.Distance(gameObject.transform.position, endPoint))));
}

else if (flag && Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude))
{
flag = false;
Debug.Log("I am here");
}
}

Answer

Assuming that this code is working properly and all you want to do is make it work in 2D

RaycastHit should be RaycastHit2D

Ray should be Ray2D.

Physics.Raycast should be Physics.Raycast2D

All you do is add 2D to the end of those API then changing all your colliders to colliders 2D in the Editor. For example, Box Collider should be replaced with Box Collider 2D.

Replace:

RaycastHit hit;
Ray ray;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out hit))
{
    flag = true;
    endPoint = hit.point;
    endPoint.y = yAxis;
    Debug.Log(endPoint);
}

with

Vector2 ray = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray, Vector2.zero);
if (hit)
{
    flag = true;
    endPoint = hit.point;
    endPoint.y = yAxis;
    Debug.Log(endPoint);
}
Comments