+1 vote

Hello, first of all, i'd like to state that i'm still a beginner.

My question is how can i write a code for collision between a specific kinematic body and a specific object(static). (i want to make a bouncer that my main character can interact with
). If you write the code too, that will be most appreciated.
Thank you

in Engine by (38 points)

1 Answer

+2 votes
Best answer

My question is how can i write a code for collision between a specific kinematic body and a specific object(static)

The Kinematic body has 2 collision functions move_and_slide() and move_and_collide(). The move and collide is what you want most of the time.

extends KinematicBody

#Here I make the gravity vector
var Gravity= 9.8 * Vector3.DOWN 
var Velocity = Vector3() #This is what direction the object is moving

#By using negative gravity it will bounce in the opposite direction
var BounceHight = 20 * -Gravity
#Inside the physics step I use move and collide and the gravity as input
func _physics_process(delta):
    #For now Gravity is the only thing effecting velocity
    Velocity = (Velocity + Gravity) * delta
    var collision = move_and_collide(Velocity)

    if collision :
        var ObjectCollidedWith = collision.collider as StaticBody

        if ObjectCollidedWith.is_in_group("Bouncy") :
            Velocity =  BounceHight

This is just a simple code example, you will want to look up what velocity is in the real world to understand how to use it.

by (1,445 points)
selected by

sorry i had a mistake in my question, my game is a 2D game, so its kinematicbody2D.
what will be the changes in this situation to the code written above?
Thank you

Vector2 instead of Vector3. That is all.

its giving me an error at this line of code:

var ObjectCollidedWith = collision.collider as StaticBody

The error says: "Expected end of statement (var)"

any idea how to fix it?

Thanks

Sorry, about that. I use Godot 3.1 Alpha 2 that has optional typing. Just remove the as StaticBodythis just tells the engine what kind of data type the variable will be.

var ObjectCollidedWith = collision.collider

In Godot 3.1 you will be able to tell variables what they should be, this helps a lot with code auto completion.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.