My first small project; sorry about the basic question, I'll give you an overview of my setup.
I have a player (CharacterBody2D) and a ball (Area2D)

The code I have working allows my player to run around and pick up my ball. The ball sticks close to the player and then the player can move a target in a radius around them and click to fire the ball in that direction.

the main bits of relevant code below
set angle (on player) =ball.direction = (get_global_mouse_position() - self.global_position).normalized()
moving ball (ball - called every frame if ball is kicked ) = self.global_position += direction * speed * delta

With this logic the ball fires correctly but will obviously just keep going forever. What would be the correct way to set a power or distance? I want to use a power variable I have set up to change it and my initial idea was to set an 'end point' vector2 and either check it at the movement script that runs every frame but I just can't figure out generating that vector2 point or if that's even the way to go

Will attach more code and / or videos if needed

  • xyz replied to this.

    bowman290 Each frame you add a certain vector to the position. Accumulate the length of this vector in a dedicate variable, and when accumulated value becomes larger than wanted distance - stop the movement.

      xyz
      Thanks, i guess this is the bit I'm stuck on:

      Accumulate the length of this vector in a dedicated variable

      • xyz replied to this.

        bowman290

        In your code there's this line that moves the object:
        self.global_position += direction * speed * delta

        It moves it by adding a certain delta vector to the current position.
        Additionally add the length of this delta vector to some variable each frame. This variable will effectively represent the distance travelled so far.

        So just check if the distance travelled so far exceeds the range and if yes then stop moving.

          Not sure if this is the 'correct' way to handle this but I have it working by doing something like this should anyone find this later. will now change it so the 20 is controlled by a power variable

          if traveledDistance < 20:
          			owner_name = ""
          			self.position += direction * speed * delta
          			traveledDistance = self.position.distance_to(startPosition)
          		else:
          			traveledDistance = 0
          			ballKicked = false

          xyz ah you replied just as i sorted it 🙂 thanks for your help by the way

          • xyz replied to this.

            bowman290 Your solution will work fine for strictly linear movement but if the thing is not moving linearly then the travelled distance will not be correct. You in fact measure the distance from the source, not the travelled distance. When accumulating actual movement increments, you get the correct travelled distance no matter what the trajectory is.