0
\$\begingroup\$

I have one object, a knight, that I click on and want to move around on terrain.

private void OnMouseDown()
{        
   if (Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit, 10000))
    {
        if (unitSelected)
            MoveUnit(hit);
        else if (unitSelected && hit.collider == home)
            GoHome(hit);
     }
}

And

private void OnMouseDown()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit))
            MoveUnit(hit);
    }
}

Both scripts work fine when clicking on the terrain.

The Problem

I want to click on different objects and send the knight towards whatever object I click on.

The knight does NOT move, though the object I click on registers a click (all objects have colliders).

Is Raycast the most appropriate way to do this? Checking another users question similar to mine, (how-to-move-one-object-to-another-objects-position) they seem to use a method similar to "Vector3.MoveTowards".

EDIT:

Moving my code from "OnMouseDown" to "Update" solves that issue. but is there a reason why OnMouseDown won't work or even how to make it work? I was trying to limit my code from going into Update as that's called every frame.

\$\endgroup\$
  • 2
    \$\begingroup\$ By the way, the else if statement in your first code block will never run since if unitSelected is true the first if statement will run, and if it is false the else if cannot run anyways. \$\endgroup\$ – Charanor Aug 19 '18 at 11:59
  • 1
    \$\begingroup\$ Can you clarify what object each of the scripts above is attached to, and show us how you've defined MoveUnit()? \$\endgroup\$ – DMGregory Aug 19 '18 at 12:56
1
\$\begingroup\$

I would highly suggest not having multiple OnMouseDown methods, as conflicts might arise. It would probably be best to send the knight to the hit position, and not the "object" itself. Physics.Raycast wont care if its terrain or an object, if it hits something it will return a position.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.