Hi guys,
I'm trying to set up my player so that it will bounce off of the head of enemies, very similar to Mario's physics. However, as you can see in the video, this does not always happen:
Here is my code:
extends KinematicBody2D
export (float)var GravityPull = 980
export (float)var GravityMultiplier = 1.0
export (float)var MoveSpeed = 200
export (float)var RunMultiplier = 1.25
export (float)var JumpHeight = -400
export (float)var BounceAmount = -300.0
export (int) var DeathFallAmount = 1500
export (Vector2) var Bounds = Vector2(0, 0)
var velocity = Vector2()
var gravity = 0
var lastPosition = Vector2()
var grounded = false
var facing
var currentPosition
var bouncePlayer = false
var playerWidth = 32
enum direction {left, right, up, down}
func _physics_process(delta):
# update gravity
update_gravity(delta)
# store the last position
if is_on_floor():
lastPosition = position
# check for death
check_for_death()
# get input
get_input()
move_and_slide(velocity, Vector2(0, -1))
if(bouncePlayer):
velocity.y += BounceAmount
bouncePlayer = false
currentPosition = position
if position.x <= Bounds.x:
position.x = Bounds.x
elif position.y <= Bounds.y:
position.y = Bounds.y
# update the gravity
func update_gravity(delta):
gravity = (GravityPull * GravityMultiplier) * delta
if is_on_floor():
velocity.y = 0
grounded = true
else:
velocity.y += gravity
grounded = false
# this function checks for death of the player by falling out of bounds
func check_for_death():
if position.y >= DeathFallAmount:
# respawn the player at its last position determined by direction its facing
if facing == direction.left:
position.x = lastPosition.x + 32
position.y = lastPosition.y
elif facing == direction.right:
position.x = lastPosition.x - 32
position.y = lastPosition.y
# get input from the user
func get_input():
if Input.is_action_pressed("ui_left"):
if Input.is_key_pressed(KEY_Z):
velocity.x = -MoveSpeed * RunMultiplier
else:
velocity.x = -MoveSpeed
if is_on_floor():
facing = direction.left
elif Input.is_action_pressed("ui_right"):
if Input.is_key_pressed(KEY_Z):
velocity.x = MoveSpeed * RunMultiplier
else:
velocity.x = MoveSpeed
if is_on_floor():
facing = direction.right
else:
velocity.x = 0
if Input.is_key_pressed(KEY_X) and is_on_floor():
velocity.y += JumpHeight
# detect if the player touched an enemy's head
func _on_Feet_body_entered(body):
# see if the body that the player's feet is touching is an enemy that they should bounce off of
if body.is_in_group("BounceEnemy"):
#if position.y + $Sprite.scale.y <= body.position.y + body.get_node("Img").scale.y:
bouncePlayer = true
#body.queue_free()
Does anybody have any idea why this might be? I've been working at it all night and just can't seem to find the answer! Any help and advice is appreciated!