Bounding/restricting a variable

I’ve been trying to have a projectile bounce off a wall. It works for the most part

Example


x = x + 5*directionVector

if x>400 then directionVector = -directionVector end

If I use larger variables or animators the x variable can escape my limits and disappear.

I’d tried the following:

https://love2d.org/wiki/Clamping

Which didn’t work.

My current solution is to add something like this:

if x>30 then x=x-30.

Is there a better solution?

How does it escape? You've reversed the directionVector, so I'd expect to come back!

Is it just alternating back and forth so fast that it skips the visible screen in both directions?

Leaving aside reversing, the max/min method will work to clamp a value. But that alone won't make it bounce back.

Your approach sounds about like what I'd do. You might try the following, so that the bounce-back starts at the wall (unless it ends up feeling MORE wrong):

if x > 400 then
    x = 400
    directionVector *= -1
end

(The *= -1 is just a shorthand way to do the same thing you already did.)

1 Like

Hi Morgan,

So I ran it again and printed x to console and it gets caught outside 400 at like 500
(when I removed if x>30 then x=x-30.)

I think if x increases really fast it overshoots 400 and then when:

if x > 400 then directionVector *= -1

runs it makes directionVector oscillate back and forth between 1 and -1.

Your solution works to keep it in bounds but I want to projectile to rebound off the wall and not just stop.

Thanks for the shorthand tip. I'll start using it.

If it gets far enough out that it can't return to the screen in one frame, then you might need instead:

directionVector = -math.abs(directionVector)

That won't oscillate.

(On the left edge, do the same with x < 0 and no - sign.)

1 Like