Odd setAngle problem

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
Nexion
Prole
Posts: 46
Joined: Fri Sep 05, 2008 1:40 pm

Odd setAngle problem

Post by Nexion »

I'm trying to make a rectangle shape simply point at (the end of it) the mouse position, but both ways that I've tried give me really funky results when they should work just fine.

Code: Select all

function update(dt) 
	world:update(dt)
	
	mPosX, mPosY = love.mouse.getX(), love.mouse.getY()
	mPosY = mPosY - 768
	bPosX, bPosY = LBarrelBody:getX(), LBarrelBody:getY()
	bPosY = bPosY - 768
	LBarrelBody:setAngle(math.deg(angleBetween(bPosX, bPosY,mPosX,mPosY)))
end

function angleBetween(ax, ay, bx, by)
	local dotproduct, lengtha, lengthb, result;

	dotproduct = (ax * bx) + (ay * by);
	lengtha = length(ax,ay);
	lengthb = length(bx,by);

	result = math.acos( dotproduct / (lengtha * lengthb) );

	if dotproduct < 0 then
		if result > 0 then
			result = result + 3.14159;
		else
			result = result - 3.14159;
		end
	end
	
	return result;
end

function length(x,y)
	return math.sqrt(x*x+y*y)
end
That was the first way I tried, and it does rotate the rect, but the angles seem to be inverted and not exact. I tried inverting the angle but that didnt help any.

I'm trying to do this without any outside libraries if I can help it.
User avatar
mön
Prole
Posts: 13
Joined: Thu Sep 18, 2008 8:53 am
Location: Zurich
Contact:

Re: Odd setAngle problem

Post by mön »

hello

math.atan2(y, x) is really useful to rotate things around other things because it gives you the right values even when x / y are negative. hope the example helps...

Code: Select all

-- Example: Rotating according to the mouse position

function load()
    image = love.graphics.newImage("images/love-ball.png", love.image_optimize)
end

function update(dt)
    ballX, ballY = 200, 200
    local mouseX, mouseY = love.mouse.getPosition()
    local x, y = mouseX-ballX, mouseY-ballY
    ballAngle = math.deg(math.atan2(y, x))
end

function draw()
    love.graphics.draw(image, ballX, ballY, ballAngle)
end
User avatar
Nexion
Prole
Posts: 46
Joined: Fri Sep 05, 2008 1:40 pm

Re: Odd setAngle problem

Post by Nexion »

Ugh... You know I tried using atan2 but it didnt work.
Your code works perfectly though. Thank you.
Mr. Strange
Party member
Posts: 101
Joined: Mon Aug 11, 2008 5:19 am

Re: Odd setAngle problem

Post by Mr. Strange »

For what it's worth, using the dot product to find the angle between vectors is really only useful if both vectors are normalized first.

However, that doesn't get around the fact that you're limited to pi, whereas math.atan2 also gives you correct quadrant information.

--Mr. Strange
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot] and 4 guests