Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extends KinematicBody2D
- # Our accumulated motion on the X axis
- var xaccum
- # Track if we're dragging a sprite
- var mouse_down
- # These are the width and height of the sprite
- var twidth
- var theight
- # A default fall speed (like gravity, but velocity instead of acceleration)
- const STARTING_SPEED = 100.0
- # A velocity vector that we'll use for calculations below
- var velocity = Vector2()
- func _ready():
- # This object will use input and fixed-timestep physics
- set_process_input(true)
- set_fixed_process(true)
- # Initialize our variables
- xaccum = 0
- twidth = get_node("Sprite").get_texture().get_width()
- theight = get_node("Sprite").get_texture().get_height()
- mouse_down = false
- velocity.y = STARTING_SPEED
- func _fixed_process(delta):
- # The object will fall until it hits the bottom of the world or another object
- var motion = velocity * delta
- # Test if we've accumulated enough movement to "jump" one grid square,
- # If we have, then we'll add that much movement to our motion vector.
- if abs(xaccum) > twidth:
- motion.x = twidth * sign(xaccum)
- xaccum -= twidth * sign(xaccum)
- else:
- motion.x = 0
- # Move the object as much as possible
- motion = move(motion)
- # If we're colliding (with the wall or another object),
- # then we need to modify our motion vector.
- # See the Godot wiki for how and why this works:
- # https://github.com/okamstudio/godot/wiki/tutorial_kinematic_char#problem
- if is_colliding():
- var n = get_collision_normal()
- motion = n.slide(motion)
- move(motion)
- # If the mouse button has been released,
- # we can stop worrying about motion on the X axis
- if not mouse_down:
- xaccum = 0
- func _input(event):
- # Create a rectangle covering the entire sprite area
- var gp = get_global_pos()
- gp.x -= twidth/2
- gp.y -= theight/2
- var gr = Rect2(gp, Vector2(twidth, theight))
- # If the left mouse button is pressed while over the object,
- # all we do is set our state variable. If it's released anywhere,
- # we clear that same variable.
- if event.type == InputEvent.MOUSE_BUTTON and event.button_index == 1:
- if gr.has_point(event.pos):
- mouse_down = event.pressed
- get_tree().set_input_as_handled()
- elif mouse_down and not event.pressed:
- mouse_down = false
- # If the user drags while holding the left mouse button,
- # that's our signal to start accumulating motion.
- if event.type == InputEvent.MOUSE_MOTION and mouse_down:
- xaccum += event.relative_x
- get_tree().set_input_as_handled()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement