Search code examples
collisiongodot

How to bounce Kinematic Body 3d (godot) whenever it collides with a gridmap, static body or another kinematic body?


I have a kinematic body which moves with a virtual joystick. What I want is that my kinematic body should bounce off (like the ball in air hockey does when it hits the walls or the striker). I have my gridmap in a group called as "walls" . Here is my code for the player :

extends KinematicBody

var acceleration = 10
var topspeed = 40
onready var joystick = get_parent().get_node("Joystick/Joystick_button")
var vel = Vector3()
var speed = 10
var target_dir = Vector2(0, 0)
var a 
var b

func _ready():
    pass 

func _physics_process(delta):
    #var target_dir = Vector2(0, 0)
    target_dir = -joystick.get_value()
    if joystick.ongoing_drag != -1:
        a = -joystick.get_value()
    if joystick.ongoing_drag == -1 and joystick.i != 0:
        target_dir = a



    vel.x = lerp(vel.x, target_dir.x * speed , acceleration * delta)
    vel.z = lerp(vel.z, target_dir.y * speed , acceleration * delta)



    #vel = move_and_slide(vel, Vector3(0, 1, 0))
    var collision = move_and_collide(vel * delta)
    if collision:
        vel = vel.bounce(collision.normal)

Edit : The vel.bounce() used at last does not satisfy the requirements as it returns a very low bounce but I want it to bounce zig zag between the walls until I change the direction with my joystick. Or putting in other words , I want the movement of my Kinematic body to be exactly like the ball's movement in Flaming core Game (click the link to see its gameplay) like how the ball bounces after colliding with the walls or the enemy.


Solution

  • Try chagne these line:

    vel.x = lerp(vel.x, target_dir.x * speed , acceleration * delta)
    vel.z = lerp(vel.z, target_dir.y * speed , acceleration * delta)
    

    to these:

    vel.x += target_dir.x * acceleration * delta
    vel.x = min(vel.x, topspeed)
    vel.z += target_dir.y * acceleration * delta
    vel.z = min(vel.z, topspeed)
    

    And adjust the acceleration if needed.