I did this last week teaching my son to code Pong funnily enough. It’s just: velocity.x = -velocity.x
ps. personally I would make adirection unit vector with a speed scalar but velocity is fine too.
thank i gonna sleep less dumb this night
Lgdn | 2021-09-22 14:27
I really can’t figure it out. Even with velocity.x = -velocity.x it dosent work ! In fact, when i use this, it dosent switch direction even once…
dany_pitre | 2021-09-23 14:47
Well, you’ve got if is_on_floor() and is_on_wall()- with an “and” that might never evaluate as true. Put a print within the branch to check. It sounds like an or would be more appropriate.
If not, check the reverse, that it’s not being called multiple times.
Here’s my son’s code from the Pong game I mentioned in case it helps. This is working fine:
func bounce():
if transform.origin.y < ball_size or transform.origin.y > screen_size.y - ball_size:
direction.y = -direction.y
func _physics_process(delta):
bounce()
goal()
move_and_slide(direction.normalized() * speed * delta)
if get_slide_count():
direction = -direction
DaddyMonster | 2021-09-23 16:10
Ok ! This gave me an Ideal that will anyway be usefull for the rest of the game.
I created an Area2D that I will put on certain walls that I want my player to bounce of.
the problem that i got now (yea, sorry, I’m new to game dev with coding!) is that if my Area 2D is not somehow away from my wall, the player will detect the wall firts. Even if the area 2d is slighty befor the wall…
Here is the code in my area 2d:
func _on_Area2D_body_entered(body: Node) -> void:
if body == Global.Player:
body.bounce()