Throwing a rigid body projectile, hold to increase force

Attention Topic was automatically imported from the old Question2Answer platform.

I’m designing a projectile attacks for my speccy platformer.

Currently I’m using a rigid body for a rock, which gets instanced at player location each time ‘shoot’ is pressed.

extends RigidBody2D

var stone_speed = 200
if get_node("../Player").movingright == true:
apply_impulse(Vector2(), Vector2(stone_speed, 70))
else:
apply_impulse(Vector2(), Vector2(-stone_speed, -70))

What I need is to hold ‘shoot’ for 2 seconds max to increase the speed of throw, to make it fall closer of fly farther.
I’m kind of at a loss how to do that (still being a beginner in gdscript).

Also, right now if movingright == true, the stone is instanced just falling onto the ground. But if it is false, the stone is flying to the left, not sitting still. Why can that be?

const DEFAULT_SPEED = 200
const SPEED_INCREASE_PER_FRAME = 1

var throw_speed = DEFAULT_SPEED
var hold_time = 0.0

func throw_rock():
hold_time = 0.0
var new_rock = rock_scene.instance()
new_rock.stone_speed = throw_speed

throw_speed = DEFAULT_SPEED

func _physics_process(delta):
if Input.is_action_pressed("shoot"):
if hold_time < 2.0:
throw_speed += SPEED_INCREASE_PER_FRAME
hold_time += delta
elif Input.is_action_just_released("shoot"):
throw_rock()

Holding down the “shoot”-key will increase the throw_speed for 2 seconds, after that, only the hold_time will increase. Releasing the “shoot”-key will instance the rock and reset the variables hold_time and throw_speed to their defaults.

No idea regarding your other issue (when movingright == true) though. Theoretically that should work. It’s hard to debug however without seeing your project and code.

Thank you so much!!

new_rock.stone_speed = throw_speed

Did you mean
new_rock.speed = throw_speed
?
And I should add this to my existing

apply_impulse(Vector2(), Vector2(stone_speed, 70))

is that right? Because I need to give it impulse, right?

verbaloid | 2020-02-03 22:20

It should work without any changes (apart from the path to the rock scene of course), if the script attached to your rocks looks like the one given in your question. There the variable containing the speed is named stone_speed, so my script is instancing a new rock scene, then overwrites this exact variable with a new value. Afterwards the add_child-call should trigger the ready-function in your rock-scene, which then applies this new_value as an impulse once (and only once).

njamster | 2020-02-04 14:13