Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Pomelo |
I want the Player (KinematicBody2d) to represent a moving ball, so when it reaches the floor it should bounce a couple of times and then stop. I have tried implementing this in many ways, but a problem always arises. For example, with the collision check from move_and_collide, the problem is that when the character is allready on the floor, it keeps detecting collisions, even if i use not self.is_on_floor and not self.is_on_wall in the if conditional. I also tried turning off gravity when player is on the floor. this is the relevant part of the code:
const FLOOR_NORMAL = Vector2.UP
var velocity := Vector2.ZERO
export var acceleration := 100.00
export var friction := 40.00
export var max_speed := 100.00
export var gravity := 200.00
export var max_fall_speed := 1500.00
export var bounce_speed := 100
func _physics_process(delta: float) -> void:
var collision = move_and_collide(velocity * delta)
var direction := get_direction()
velocity = calculate_move_velocity(velocity, direction, acceleration)
if collision and not self.is_on_floor() and not self.is_on_wall():
velocity.y= - bounce_speed
clamp_velocity()
velocity = move_and_slide(velocity, FLOOR_NORMAL)
func get_direction() -> float:
return Input.get_action_strength("move_right") -
Input.get_action_strength("move_left")
func calculate_move_velocity(
velocity: Vector2,
direction: float,
acceleration: float
) -> Vector2:
var out := velocity
out.x += acceleration * direction * get_physics_process_delta_time()
if not self.is_on_floor():
out.y += gravity * get_physics_process_delta_time()
if direction == 0:
out.x = move_toward(out.x, 0, friction * get_physics_process_delta_time())
return out
func clamp_velocity () -> void:
velocity.y = clamp(velocity.y, -max_fall_speed, max_fall_speed)
velocity.x = clamp(velocity.x, -max_speed, max_speed)
With this version of the code the Player bounces only once and then, almost randomnly, bounces out of nowhere when moving, and then most of the times when it collides with a wall. The Player Scene is just a KinematicBody2d with a CollsionShape2d and an AnimatedSprite as children. The shape of the Player (and of the collsision shape) is a perfect circle, and it is colliding with square MapTiles.
The bouncing only once is not for now, part of the problem. Thanks in advance