0
votes

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.

1
I don't get why Vector3.bounce does not satisfy your requirements, it should keep total magnitude of your speed vector the same and just change the direction? If you want more speed you can always multiply your vector with a scalar? - unlut
It just bounces way too low when I use vel.bounce() method . Am I doing a mistake in using the wrong Vector3 with the bounce method ? - Dev
Maybe check values of vel and vel.length before and after bounce, vel.length should be same. Also is this slow down only happens when there is a collision? - unlut
yes it is , it slows down after the collision, the bounce is wayy tooo low, and not like the flaming core's ball (if you saw the gameplay) - Dev
Maybe your ball is colliding multiple times while trying to get away from obstacle, thus performing bounce multiple times. Is that the case? - unlut

1 Answers

1
votes

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.