Player needs to switch direction when hit the wall

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

hi ! I’m doing an autorunner platforming game, and I need my player to switch direction when he hits the wall.

The problem that I have is that it only works the first time. After that, his velocity goes to -0 and he stops… any advice?

Here is the code:

func _ready() -> void:
	velocity.x = max_speed
func _physics_process(delta):
	if velocity.y > 0 and not is_on_floor():
	elif velocity.x != 0:

	if is_on_floor() and is_on_wall():
		velocity.x = velocity.x * -1

hello, you should try another calculation,
instead of “velocity.x = velocity.x * -1” you should try “velocity.x = velocity.x - velocity.x * 2”

Lgdn | 2021-09-22 13:45

Oh i’m sorry, I’ve made a mistake. either with velocity.x * -1 or velocity.x - velocity.x *2 word.

The code is:

func _ready() -> void:
	velocity.x = max_speed
    func _physics_process(delta):
    	if velocity.y > 0 and not is_on_floor():
    	elif velocity.x != 0:
    	if is_on_floor() and is_on_wall():
    		velocity.x = max_speed * -1

This code works only one time

dany_pitre | 2021-09-22 13:52

:bust_in_silhouette: Reply From: DaddyMonster

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):
    	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:

dany_pitre | 2021-09-24 13:49