Search code examples
godotgdscript

I tried to shoot an object towards cursor position, but it has a problem


I'm a beginner in Godot I want to shoot an object that is already in the game towards where the cursor's position is, and the method I created for it works fine but depending on the distance between the object and the cursor the speed changes. can anyone please help me make the speed constant?

I used this:

func _process(_delta):
    if Input.is_action_just_released("tap"):
        var mousepos = get_viewport().get_mouse_position()
        var ballpos = self.get_position()
        var x = mousepos.x - ballpos.x
        var y = mousepos.y - ballpos.y
        velocity = Vector2(x,y)

Solution

  • You can normalize your vector, which gives you a vector of unit length:

    velocity = Vector2(x,y).normalize()
    

    And then scale it by the speed you want:

    velocity = Vector2(x,y).normalize() * speed
    

    Where speed is a previously defined variable or constant. Something like this will do:

    var speed := 100.0
    

    You, of course, will want to tweak the value. So perhaps you want to export it so you can set it form the inspector:

    export var speed := 100.0
    

    By the way, you can rewrite the code you have to this:

            var mousepos = get_viewport().get_mouse_position()
            var ballpos = self.get_position()
            velocity = mousepos - ballpos 
    

    Adding the changes suggested above we have:

            var mousepos = get_viewport().get_mouse_position()
            var ballpos = self.get_position()
            velocity = (mousepos - ballpos).normalize() * speed
    

    Which you can rewrite to this:

            var mousepos = get_viewport().get_mouse_position()
            var ballpos = self.get_position()
            velocity = ballpos.direction_to(mousepos) * speed