Page 1 of 1

Issue with Flipping Sprite

Posted: Thu Mar 22, 2018 11:41 pm
by Zorochase
Hello,
My character's sprites all face right, and I don't want to have to create a separate sheet with left-facing sprites. I tried doing this:

Code: Select all

function Player:draw()	    
	love.graphics.draw(self.image, self.x, self.y, 0, self.direction, 1) -- self.direction = -1 when the player presses 'left'
end
It only kind of works. The sprite flips, but jolts forward, like so:
run.gif
run.gif (79.93 KiB) Viewed 4064 times
Here's what the update function looks like
(full implementation not shown; just what controls left/right movement):

Code: Select all

function Player:update(dt)
	if love.keyboard.isDown('left') then
		self.x = self.x - (dt * self.xSpeed) -- self.xSpeed = 150
                self.direction = -1
	end
	if love.keyboard.isDown('right') then
		self.x = self.x + (dt * self.xSpeed)
		self.direction = 1
	end
end
Is it because I'm drawing to a canvas (512x288)?
How do I keep it from doing this (preferably without removing the canvas)?

Re: Issue with Flipping Sprite

Posted: Thu Mar 22, 2018 11:49 pm
by ivan
It's because your sprite offset.
You are drawing the sprite from the top-left corner.
If you expect it to flip along the center you need to offset the sprite by half its width.

Re: Issue with Flipping Sprite

Posted: Fri Mar 23, 2018 1:04 am
by Jasoco
Yeah like Ivan said, just offset the x-offset to half the sprite width and adjust the draw x-offset to the same amount so it draws within the same box.

love.graphics.draw(self.image, self.x + (self.image:getWidth() / 2), self.y, 0, self.direction, 1, (self.image:getWidth() / 2), 0)

You can cache the self.image:getWidth() / 2 part as a variable if you want to or know exactly the size of all your sprites anyway just to avoid all the :getWidth() calls if you want.

Re: Issue with Flipping Sprite

Posted: Fri Mar 23, 2018 10:58 pm
by Zorochase
Jasoco wrote: Fri Mar 23, 2018 1:04 am Yeah like Ivan said, just offset the x-offset to half the sprite width and adjust the draw x-offset to the same amount so it draws within the same box.

love.graphics.draw(self.image, self.x + (self.image:getWidth() / 2), self.y, 0, self.direction, 1, (self.image:getWidth() / 2), 0)

You can cache the self.image:getWidth() / 2 part as a variable if you want to or know exactly the size of all your sprites anyway just to avoid all the :getWidth() calls if you want.
This seems to have worked. Thanks for the help.