Search code examples
game-physicsgodotgdscript

Stopping movement of sprite if it's at the same position as the mouse


I am trying to make a sprite stop moving when it's x and y are the same as the mouse's.

For some reason, once the image is in the same position as the mouse the image starts going back and forth in the same axis really fast. I need to make it stop moving.

func _physics_process(delta):
    var move_vec = Vector2()
    var look_vec = get_global_mouse_position() - global_position
    //this gets the mouse and sprite position

    if move_vec != look_vec: // if mouse and sprite are not the same then move.
        move_vec = look_vec
        move_vec = move_vec.normalized()
        move_and_collide(move_vec * speed * delta)
        global_rotation = atan2(look_vec.y, look_vec.x)
    else:
        pass`enter code here`

Solution

  • Ah this happened to me while working in game development with Unity.

    The problem is that you're overshooting by very tiny amounts.

    Say you want to get to position 0. You are hitting postions like 0.00004 then -0.0524 then 0.00242

    Basically, you're oscillating near zero because it's never quite equal.

    I suggest you try something like:

    if move_vec - look_vec > someMinValue || move_vec - look_vec < -someMinValue 
    

    (this is an absolute value comparison)

    Basically, if it's within some small value, you can tell the game to relax and accept it. You may then choose to adjust the value to make it exactly equal to the desired value:

    move_vec = look_vec
    

    There are probably better answers you can come up with. The important thing here is that you understand what the issue is and can now correct in it your desired way.