Turret turning/angle example with decceleration
Posted: Tue Jun 18, 2013 5:58 pm
Left click to turn the turret.
Keywords: turret,angle,acceleration,decceleration,rotation
The code in case the demo goes down:
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