Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #This is a better way of doing movement. Instead of having if statements for every movement, you could use #Input.get_action_strength , which would return 1 if the key is pressed. This also allows you to use analogue sticks or #keys. For example is you are using a controller and press the joystick half way, you would get a decimal value. It would #work like this: velocity.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
- #So if you only press left, it will be 0 - 1 which is -1, so you move left. If you only press right it will be 1 - 0, so 1 #and you will move right. If you press both it will be 1 - 1, zero so nobody moves. You could have this in a get_direction #function and return it as a Vector2 and store it in a direction variable, so when you are calculating the velocity you #could do direction.x * speed.
- #This is a better way of doing it as it handles gravity, movement and jumping all within one calculation and has minimal if #statements. Also, the longer you hold the jump button for the higher you go, capped at your jump height which is your #speed.y. This means you can do short and heigh jumps so it feels better and smoother.
- extends KinematicBody2D
- var velocity: = Vector2.ZERO
- export var speed:= Vector2(400.0, 600.0)
- export var gravity = 3000.0
- func _physics_process(delta: float) -> void:
- # checking to see if the player has let go of the jump key
- var is_jump_interrupted: = Input.is_action_just_released("jump") and velocity.y < 0.0
- var direction: = get_direction()
- velocity = calculate_move_velocity(velocity, direction, speed, is_jump_interrupted)
- velocity = move_and_slide(velocity, Vector2.UP)
- func get_direction() -> Vector2:
- #getting the direction the player is moving in, returns 1, 0 or -1
- return Vector2(
- Input.get_action_strength("move_right") - Input.get_action_strength("move_left"),
- -1.0 if Input.is_action_just_pressed("jump") and is_on_floor() else 1.0
- )
- func calculate_move_velocity(linear_velocity: Vector2, direction: Vector2, speed: Vector2, is_jump_interrupted: bool) -> Vector2:
- # calculating final velocity
- var out = linear_velocity
- # calculating the x velocity using the max speed and direction we got earlier
- out.x = speed.x * direction.x
- #applying gravity
- out.y += gravity * get_physics_process_delta_time()
- # checking to see if we are jumping and then calculating jump velocity
- if direction.y < 0:
- out.y = speed.y * direction.y
- # canceling jump if it is interrupted
- if is_jump_interrupted:
- out.y = 0
- return out
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement