I want to be able to ‘throw’ objects with the mouse: when I release the mouse the object retains its velocity in the last direction moved.
I’ve tried implementing this in the fashion described in the two linked posts, but have a couple issues. First, that when the mouse has moved a distance, then stops, then releases, the object still moves, second that if the mouse changes throw direction mid-move or doesn’t throw directly in a straight line, the object still only moves the direction of the net motion of the mouse.
I’ve attached a video of my current (non-working) implementation, here’s the code:
[skip variable declaration, input function, draw function]
func _process(delta):
if !held:
velocity *= 0.95;
position += velocity * delta;
func drag():
position = get_global_mouse_position() + holdOffset;
func grab():
startPos = position;
startTime = Time.get_ticks_msec() / 1000.0;
color = Color.RED;
held = true;
holdOffset = - get_local_mouse_position();
func release():
velocity = (position - startPos) / (Time.get_ticks_msec() / 1000.0 - startTime);
color = Color.GREEN;
held = false;
I seem to be unable to properly use hyperlinks here, so here are the relevant links:
Related Posts:
You take into consideration the difference between your current position and your starting position, so your throw will always result in this total net difference direction.
One solution would be to cache the position from the last frame and use that instead of your starting position.
You could also set velocity to always (except when too close) move toward the mouse. Then, when you let go, your velocity will continue.
func _process(_delta):
if held:
#Get mouse position. might not need get_viewport()
var mouse_p = get_viewport().get_global_mouse_position
#get vector to the mouse
var v_to_m = mouse_p - position
#Use length squared to compare because it's slightly faster
#Change the 100 below to a different number
if v_to_m.length_squared >= 100.0:
velocity += v_to_m * 1 #Some scalar value. the strength of the throw
else:
#if too close, dampen velocity. THIS IS OPTIONAL AND MIGHT REDUCE THROW STRENGTH
velocity *= 0.9
else:
#friction
velocity *= 0.95
#gravity
velocity += 1
move_and_slide() #may use move_and_collide()