Detecting left and right facing slopes

Godot Version

4.7

Question

Hello, I’m working on a 2D platformer and have recently begun implementing special slope movement where the player speeds up while going downhill like in Sonic. The way I’ve written the code right now though, this only works for slopes that go right, and slopes that go left will slow the player down even though they move downwards. I figure if I can detect whether the slope goes left or right I could use an if statement and switch the += acceleration to a -= acceleration, but I’m not sure how to do that.

func slope_movement():
	print(velocity.x) # for testing
	velocity.x += slope_acceleration
	velocity.x = clamp(velocity.x, -slope_max_speed, slope_max_speed)
	speed = velocity.x

Check the dot product between character’s horizontal facing and the slope normal.

Could you show what that would look like in code? I’m looking at the documentation on vector math but I’m still a little confused.

Oh wait, I think I got it! It works so far anyway.

var a = transform.x.normalized()
var b = get_floor_normal()
if a.dot(b) > 0:
	_left_or_right = false
elif a.dot(b) < 0:
	_left_or_right = true

You just implemented the solution I described, so you should really mark my post.

Besides, you coded it in a redundant, pedestrian way. Your variable names are poorly chosen. a and b mean nothing and _left_or_right is confusing and doesn’t clearly signify the purpose of the variable. Remember that the results of boolean expressions can be assigned to boolean variables. The whole thing can be done in one line of code:

_facing_down_slope = get_floor_normal().dot(global_transform.x.normalized()) > 0.0