Godot 3 - How to code for specific Kinematic Body / Static body collision

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Taabta

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

:bust_in_silhouette: Reply From: MysteryGM

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.

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

Taabta | 2018-12-14 18:47

Vector2 instead of Vector3. That is all.

MysteryGM | 2018-12-15 03:06

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

Taabta | 2018-12-15 18:26

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.

MysteryGM | 2018-12-16 03:29