How do I create a kinematic body that can detect where it is hit?

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

Trying to replicate a pong game. I got the ball and the paddles moving and I’m trying to work out collisions. Both the ball and the paddle are KinematicBody2D’s. I what the ball to bounce at different angles depending on where it hits the Paddle.

Essentially, I want the ball to bounce upwards when it it’s the top part of the paddle, downwards when it hits the bottom, and straight when it hits the middle. What do you guys think is the best approach?

:bust_in_silhouette: Reply From: Sdhy

You could try looking into area2d nodes for hitboxes/hurtboxes:

I remember using 3d area nodes was confusing, but irrc, it seemed to be doing what I wanted.

You might also be able to detect which angle the ball hits the paddle at. Though I’m not sure how to do that.

This link might be relevant:
https://forum.godotengine.org/16577/how-to-detect-a-collision-with-an-area2d

But yeah, i remember it being confusing. Godot 3.2 is planning to have more user-friendly signals, though.

Thanks. I was trying with Area2d before. So what I did was assign 3 Area2d to the paddle itself which is a kinematic body. Not sure if this was the best approach since I couldn’t get it to work properly.

In the end I got it to work by checking the position of the ball relative to the position of the paddle. Here is the code in case someone is curious.

func _physics_process(delta):
var collision_info = move_and_collide(velocity * delta)
if collision_info:
	velocity.x = velocity.x * -1 # Bounce
	
	var p_pos = collision_info.collider.position
	if position.y > p_pos.y + 25 and position.y < p_pos.y + 75:
		velocity.y = abs(velocity.x)
	elif position.y < p_pos.y - 25 and position.y > p_pos.y - 75:
		velocity.y = -abs(velocity.x)
	else:
		velocity.y = 0
	velocity = velocity.normalized() * speed

The paddle measures 10 by 150 pixels

hidemat | 2019-07-30 23:50