Page 1 of 1

Turret turning/angle example with decceleration

Posted: Tue Jun 18, 2013 5:58 pm
by markgo
Left click to turn the turret.

Keywords: turret,angle,acceleration,decceleration,rotation

The code in case the demo goes down:

Code: Select all

turn_line = {400,300,0,0}
look_angle= 0
turn_speed= 2
accel     = 0
turret_r  = 100

function love.mousepressed(x,y,b)
	if b == 'l' then 
		turn_line[3],turn_line[4] = x,y
	end
end

function love.update(dt)
	x,y,x2,y2 = unpack(turn_line)
	old_turn  = turn_angle
	turn_angle= math.atan2( y2-y, x2-x ) % (2*math.pi)
	look_angle= look_angle % (2*math.pi)
	
	min_disp_angle = turn_angle-look_angle
	if min_disp_angle < -math.pi then min_disp_angle = 2*math.pi+min_disp_angle end
	if min_disp_angle > math.pi then min_disp_angle = -2*math.pi+min_disp_angle end
	
	if math.abs(min_disp_angle) < 0.01 then turn_speed = 0; accel = 0
	elseif old_turn ~= turn_angle then
		if min_disp_angle < 0 then turn_speed = -2 
		elseif min_disp_angle > 0 then turn_speed = 2 end
		
		-- http://hyperphysics.phy-astr.gsu.edu/hbase/mot.html
		accel      = -(turn_speed^2)/(2*min_disp_angle)
	end
	
	dv         = accel*dt
	look_angle = look_angle + dt*(turn_speed + dv/2)
	turn_speed = turn_speed+dv
end

function love.draw()
	love.graphics.line(unpack(turn_line))
	
	dx,dy = math.cos(look_angle),math.sin(look_angle)
	dx,dy = dx*turret_r,dy*turret_r
	love.graphics.line(400,300,400+dx,300+dy)
	
	love.graphics.print('Displacement angle: '..math.deg(min_disp_angle),0,0)
	love.graphics.print('Turn angle: '..math.deg(turn_angle),0,15)
	love.graphics.print('Look angle: '..math.deg(look_angle),0,30)
end

Re: Turret turning/angle example with decceleration

Posted: Tue Jun 18, 2013 6:14 pm
by NightKawata
Where's the turret? All I see are a bunch of demos including parallax scrolling and isotometric maps.
Plus, this is a demo, not a youtube video; 's with the keywords? :P

EDIT: Oh. You fixed it.

Re: Turret turning/angle example with decceleration

Posted: Wed Jun 19, 2013 1:02 am
by Ref
OK!
So now he has a turret.
And the next thing, he probably wants to fire it.

Re: Turret turning/angle example with decceleration

Posted: Sat Jun 22, 2013 9:58 am
by jjmafiae
nice :3