GodotCourse/examples/PlatformTemplate/scripts/playermovement.gd

98 lines
2.8 KiB
GDScript

extends CharacterBody2D
const SPEED = 200.0
const JUMP_VELOCITY = -300.0
const PUSH_FORCE = 80.0
const BLAST_SPEED = 750
var pushLeftEnabled = false
var pushRightEnabled = false
var pushTarget
var faceLeft = false
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
@onready var animated_sprite = $AnimatedSprite2D
@onready var rightRay = $RightRaycast
@onready var leftRay = $LeftRaycast
@onready var label = $Label
@onready var markerRight = $MarkerRight
@onready var markerLeft = $MarkerLeft
var bullet = preload("res://scenes/bullet.tscn")
func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y += gravity * delta
# Handle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("runleft", "runright")
if Input.is_action_just_pressed("push") && pushRightEnabled && faceLeft == false:
label.text="shove"
pushTarget.apply_central_impulse(Vector2(1,0) * PUSH_FORCE * 20)
pushRightEnabled = false
if Input.is_action_just_pressed("push") && pushLeftEnabled :
label.text="shove"
pushTarget.apply_central_impulse(Vector2(-1,0) * PUSH_FORCE * 20)
pushLeftEnabled = false
if Input.is_action_just_pressed("blast"):
var mybullet = bullet.instantiate()
mybullet.setSpeed(-BLAST_SPEED if faceLeft else BLAST_SPEED)
owner.add_child(mybullet)
mybullet.transform = markerLeft.global_transform if faceLeft else markerRight.global_transform
if direction:
velocity.x = direction * SPEED
faceLeft = true if direction<0 else false
animated_sprite.flip_h = true if direction < 0 else false
else:
# slow the character to a stop
velocity.x = move_toward(velocity.x, 0, SPEED)
if is_on_floor():
if direction==0:
label.text="idle"
animated_sprite.play("idle")
else:
label.text="run"
animated_sprite.play("run")
else:
label.text="jump"
animated_sprite.play("jump")
move_and_slide()
# Detect colliders in the ray
if rightRay.is_colliding():
var collider = rightRay.get_collider()
if collider is Node:
if collider.is_in_group("boxes"):
pushRightEnabled = true
pushTarget = collider
else:
pushRightEnabled = false
if leftRay.is_colliding():
var collider = leftRay.get_collider()
if collider is Node:
if collider.is_in_group("boxes"):
pushLeftEnabled = true
pushTarget = collider
else:
pushLeftEnabled = false
# This represents the player's inertia
# after calling move_and_slide()
for i in get_slide_collision_count():
var c = get_slide_collision(i)
if c.get_collider() is RigidBody2D:
c.get_collider().apply_central_impulse(-c.get_normal() * PUSH_FORCE)