转自:http://blog.youkuaiyun.com/jkevin2016/article/details/52885137
local local_class = class() --这里用到云风的CLASS代码
local gr=love.graphics
local function getDistance (pointO,pointA )
distance = math.pow((pointO.x - pointA.x),2) + math.pow((pointO.y - pointA.y),2);
distance = math.sqrt(distance);
pointO,pointA=nil,nil
return distance;
end
function local_class:ctor(bg,spr)
self.bg = bg
self.spr = spr
self.dir = 0
self.renge = 0
self.power = 0
self.w2 = self.bg:getWidth()/2
self.point = {x=0,y=0}
self.offset = {x=0,y=0}
self.press = false
end
function local_class:update()
end
function local_class:setPoint(x,y)
self.point.x ,self.point.y = x,y
end
function local_class:draw()
gr.draw(bg,self.point.x,self.point.y,0,1,1,110,110)
gr.draw(center,self.point.x+self.offset.x,self.point.y+self.offset.y,0,1,1,48,48)
end
function local_class:touchpressed( id, x, y, dx, dy, pressure )
local radius = self.w2
local dis = getDistance({x=x,y=y},self.point);
if dis < radius then
self.press = true
self.offset.x = (x-self.point.x)
self.offset.y = (y-self.point.y)
end
end
function local_class:touchreleased( id, x, y, dx, dy, pressure )
if self.press then
self.offset.x = 0
self.offset.y = 0
end
self.press = false
self.dir = 0
end
function local_class:touchmoved( id, x, y, dx, dy, pressure )
if self.press then
local radius = self.w2
local dis = getDistance({x=x,y=y},self.point);
local angle = math.acos ( (x - self.point.x)/dis );
if dis>radius then
if ( y > self.point.y ) then
self.offset.x = radius*math.cos(angle)
self.offset.y = radius*math.sin(angle)
else
self.offset.x = radius*math.cos(angle)
self.offset.y = -(radius*math.sin(angle))
end
else
self.press = true
self.offset.x = (x-self.point.x)
self.offset.y = (y-self.point.y)
end
if dis > self.renge then
if (y > self.point.y) then
self:__checkDirection(angle);
else
self:__checkDirection(-angle);
end
else
self.dir = 0
end
self.power = dis / radius
end
end
function local_class:getDirection()
return self.dir
end
function local_class:__checkDirection(angle)
local dir = 0
local M_PI=math.pi
if (angle >= -M_PI/8.0 and angle <= M_PI/8.0) then
dir = 6;
end
--[[右边走 -八分之派 到 八分之派--]]
if (angle >= -(M_PI/8.0) and angle <= M_PI/8.0) then
dir = 6;
--[[右上方向 八分之派 到 八分之三派--]]
elseif( angle >= M_PI/8.0 and angle < 3*M_PI/8.0) then
dir = 3;
--[[上方向 八分之三派 到 八分之五派--]]
elseif( angle >= 3*M_PI/8.0 and angle <= 5*M_PI/8.0) then
dir = 2;
--[[左上方向 八分之5派 到 八分之七派--]]
elseif( angle > 5*M_PI/8.0 and angle < 7*M_PI/8.0) then
dir = 1;
--[[左方向--]]
elseif( (angle >= 7*M_PI/8.0 and angle <= M_PI) or (angle <= -7*M_PI/8.0 and angle >= -M_PI)) then
dir = 4;
--[[左下方向--]]
elseif( angle > -7*M_PI/8.0 and angle < -5*M_PI/8.0) then
dir = 7;
--[[下方向--]]
elseif( angle >= -5*M_PI/8.0 and angle <= -3*M_PI/8.0) then
dir = 8;
--[[右下方向--]]
elseif( angle > -3*M_PI/8.0 and angle < -M_PI/8.0 ) then
dir = 9;
end
self.dir = dir
end
return local_class
这里有个小例子
链接: http://pan.baidu.com/s/1boQcpVT 密码: drsm