Page 1 of 1

[Solved]Having trouble making a flail weapon

Posted: Tue Aug 18, 2015 11:24 am
by NickRock
I'm making a game where you swing the flail with the mouse, I want the distance between the player and the square to be less than 150 pixels but I can't get it done

I tried this

Code: Select all

d = math.sqrt( (spikeball.x - chain.x)^2 + (spikeball.y - chain.y)^2 )
	if d < 150 then
		spikeball.x = love.mouse.getX()
		spikeball.y = love.mouse.getY()
	end
but it doesn't really work like I expected it to work

Image

You can download the .love file here
https://www.dropbox.com/s/kmq41zsksn21e ... .love?dl=0

I hope I explained everything well :)

Re: Having trouble making a flail weapon

Posted: Tue Aug 18, 2015 11:51 am
by Nixola
I think you should use vectors, or at least some vector math:

Code: Select all

local newX, newY = love.mouse.getPosition()
local vX, vY = newX - chain.x, newY - chain.y -- let's obtain the distance along the X and Y axes
d = math.sqrt( vX * vX + vY * vY ) -- here we calculate the actual distance
if d > 150 then -- if the distance is higher than what we want 
  vX, vY = vX/d, vY/d -- here we normalize the vector (divide its componenta by its length)  making it exactly one unit long; this allows us to multiply it by whatever we want, thus making it long exactly 150 units without changing its direction. 
  vX, vY = vX*150, vY*150
end
spikeball.x = chain.x + vX -- since vX is the horizontal distance, we should add it to the chain position
spikeball.y = chain.y + vY -- same as above

Re: Having trouble making a flail weapon

Posted: Tue Aug 18, 2015 12:30 pm
by NickRock
Thank you, it makes sense now