Click to Move with mouse only moving one frame

Hi,

I’m trying to move my Player using the mouse but when I select a point it only moves one frame. If I select a point after that it moves one frame more etc.

public class Move: MonoBehaviour
{

    [SerializeField] Vector2 destination;
    [SerializeField] float moveSpeed = 4f;

    private void Start()
    {
        destination = transform.position;
    }

    private void Update()
    {
        Move();
    }

    private void Move()
    {
        if (Input.GetMouseButtonDown(0))
        {  
            destination = GetMousePosition();
            transform.position = Vector2.MoveTowards(transform.position, destination, moveSpeed * Time.deltaTime);
        }
    }

    private static Vector2 GetMousePosition()
    {
        return Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
}

If I instead place the movement logic outside of the If() statement the movement works but it breaks another logic where I Raycast to find Enemy targets. Is there any way to make the movement work with the movement logic inside of the IF() statement?

Generally the correct way is to have line 21 inside the if statement obviously, and line 22 always executed.

When you say this:

you have to be more specific.

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, especially any errors you see
  • links to documentation you used to cross-check your work (CRITICAL!!!)

To find more, debug it! Here’s how:

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Hi,

Let me rephrase the question. Never mind the stuff with reaycast etc.

If I use the class Mover, where the transform.position is within the IF Statement, to move my object on the screen the object only moves one frame on the screen. If I use the class Mover2 it works as I want it to.

The question is if there is a solution where I can use the Mover class with the actual move logic within the IF() Statement and how I could achive this solution.

I have attached a media file with the result of using both classes.

public class Mover : MonoBehaviour
{
    [SerializeField] Vector2 destination;
    [SerializeField] float moveSpeed = 4f;

    private void Start()
    {
        destination = transform.position;
    }

    private void Update()
    {
        Move();
    }

    private void Move()
    {
        if (Input.GetMouseButtonDown(0))
        {
            destination = GetMousePosition();
            transform.position = Vector2.MoveTowards(transform.position, destination, moveSpeed * Time.deltaTime);
        }
    }

    private static Vector2 GetMousePosition()
    {
        return Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
}
public class Mover2 : MonoBehaviour
{
    [SerializeField] Vector2 destination;
    [SerializeField] float moveSpeed = 4f;

    private void Start()
    {
        destination = transform.position;
    }

    private void Update()
    {
        Move();
    }

    private void Move()
    {
        if (Input.GetMouseButtonDown(0))
        {
            destination = GetMousePosition();
        }
        transform.position = Vector2.MoveTowards(transform.position, destination, moveSpeed * Time.deltaTime);
    }

    private static Vector2 GetMousePosition()
    {
        return Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
}

Hi!

I think the problem might be that in your IF condition you are using Input.GetMouseButtonDown(0). This will only trigger once your mouse has been pressed (and only once for each click), and for that reason it won’t give you a continuous movement.

You are probably looking for Input.GetMouseButton(0), this will be true every frame that left mouse button is pressed.

Take a look at the docs:
GetMouseButton: Returns whether the given mouse button is held down.
GetMouseButtonDown: Returns true during the frame the user pressed the given mouse button.

Hope it helps!

Also, so you know, you should never modify the Transform when using 2D physics. You should cause movement by using the Rigidbody2D API. By setting the Transform you’re bypassing physics and causing the Rigidbody to read the Transform next time the simulation runs.

What should happen is that the Rigidbody2D writes to the Transform, not the other way around.

Hi,

Thank you for the tip!

When changing to GetMouseButton it works for as long as I press the button. What I want to do is to click to select where to move and then move there without pressing the mousebutton constantly. I don’t know if I can do that with GetMouseButton in any way!!

I understand that you have already achieved that behavior with the modification you have made in Mover2, right?

The key in that solution is that you save the destination position when you click (GetMouseButtonDown) and then, by successive Updates you take it to the destination.

Anyway, you should take into account what MelvMay said and use Rigidbody to move your GameObject if you want it to behave correcty according to physics. If you do so, you should be using FixedUpdate instead of Update to perform the movement.

Take a look at how to GameObjects move using rigidbodies into Unity docs.

Hi,

I will be looking at Rigidbody after I get the logic right.

The problem with using the mover2 solution is if I want something else to call the Move logic(I will extract the movetowards method to crate a Move Function). If I place the Move logic outside the IF statement it will be called on every update which means I cannot call the move logic from a function that e.g says move to a target object.

You can with a simple modification to the “move always every frame”

Make it instead be “if I am more than x distant from destination, then move, otherwise do nothing”

That way when doing nothing, your other code can function.

You might need to suppress the other code based on having a pending destination or not, perhaps tracked by another boolean that gets cleared when the destination is reached?

It really can work however you like. Step through the logic in your mind.

Hi,

Thank you! I solved it by setting a bool for target so when I select something that I want to interact with I turn of movement! It has created some other stuff I need to handle but I think it will get me where I want to.

private void Update()
    {

        if (!hasTarget)
        {
        Move();
        }
    }
2 Likes

Now just change the body-type to Kinematic and change "transform.position = " to “myRigidbody.MovePosition(…)” and you’ll have correct physical movement.

2 Likes

I updated to “myRigidbody.MovePosition(…)” and it works great! Thanks for the tip!

2 Likes