How to keep a sprite from sliding off game screen...

So here’s my code:


displayMode(FULLSCREEN)
supportedOrientations(PORTRAIT)

function setup()
    x=WIDTH/2
    y=HEIGHT/2
end

function draw()
    background(84, 84, 84, 255)
    x=x+Gravity.x*15
    y=y+Gravity.y*15
    sprite("Space Art:Green Ship",x,y)
end

And that is it.
I am trying to design a space-like game where the ship can slide freely as you tilt the screen, and shoot astroids that move down the screen to earn points.
But in issue that I’m having is the sprite keep sliding off the screen. I was wondering if anyone could help me set up a perimeter that keeps the sprite on screen. Also, I would like the ship to shoot bullets as you tap the screen. Can anyone please help me! And by the way, I am new to Codia, and programming in general. Please help :slight_smile:

I think you want something like this;
Use the self.position to keep track of your sprites position. Also, welcome to the forums!!!

Setup function

self.position = vec2 (WIDTH/2, HEIGHT/2)
Draw function
-- set the 50 to half of your sprites size.

   if self.position.x > WIDTH -50 then
    self.position.x = WIDTH -50
    end
    if self.position.y > HEIGHT -50 then
        self.position.y = HEIGHT -50
    end
    if self.position.x < 50 then
        self.position.x = 50
    end
    if self.position.y < 50 then 
        self.position.y = 50
    end

sprite ("sprite name here", self.position.x, self.position.y)

I’ve made a game similar to this when I was first starting out (and I am far from being good). If you need any code, pm me. I have a few classes for things such as tracking device position based on rotation rate versus gravity etc.

Thanks man! I appreciate it!

@The_Waffle_Man - You’ll find your code formats nicely, if you put three ~ on a line before and after it

I would recommend using math.min and math.max instead of a bunch of bulky if statements. They work very simple, you give math.min two numbers and it returns the smallest of the two, and math.max does the opposite (returns the larger). So you can try something like this:

self.position.x = math.max(50, math.min(WIDTH - 50, self.position.x))
self.position.y = math.max(50, math.min(HEIGHT - 50, self.position.y))

Using math.max or math.min with one inside the other’s parameters can basically “clamp” the number to anything between the minimum and the maximum you want.