love2d杂记3--鼠标拖动和线条辉光

来自老外博客,鼠标拖动原文链接,发光效果原文链接

鼠标拖动

这个就是检测鼠标是否在绘图区域按下,还要注意拖动时的坐标要减去

鼠标坐标与绘图区左顶点的差值。

function love.load()
  rect = {
    x = 100,
    y = 100,
    width = 100,
    height = 100,
    dragging = { active = false, diffX = 0, diffY = 0 }
  }
end
 
function love.update(dt)
  if rect.dragging.active then
    rect.x = love.mouse.getX() - rect.dragging.diffX
    rect.y = love.mouse.getY() - rect.dragging.diffY
  end
end
 
function love.draw()
  love.graphics.rectangle("fill", rect.x, rect.y, rect.width, rect.height)
end
 
function love.mousepressed(x, y, button)
  if button == "l"
  and x > rect.x and x < rect.x + rect.width
  and y > rect.y and y < rect.y + rect.height
  then
    rect.dragging.active = true
    rect.dragging.diffX = x - rect.x
    rect.dragging.diffY = y - rect.y
  end
end
 
function love.mousereleased(x, y, button)
  if button == "l" then rect.dragging.active = false end
end

 

 线条辉光

简译:

最近我尝试找到love2d来实现线条辉光(原文make lined shapes glow),或许有其它方式,下面是我想到的。

love.graphics.setColor(r, g, b, 15)

for i = 7, 2, -1 do
  if i == 2 then
    i = 1
    love.graphics.setColor(r, g, b, 255)
  end
  
  love.graphics.setLineWidth(i)
  -- draw lined shape here
end

 

上面的代码多次绘图,每次使用不同的线条宽度i。 一共绘制六次,每次的线条宽度为7, 6, 5, 4, 3, 1.

除了最后一次外,线条的alpha被设为15(最后一次是255).love默认alpha重叠,对线条来说颜色会越来越深,

就产生了辉光的效果。  最后一条线的alpha 是255,作为光源。

下面我把上面的想法写成了函数glowShape,你可以自己测试想要的效果。

A couple of glowing shapes.

最后你需要检测机器是否支持framebuffer,若支持就使用,这会提高很大的速度。

完整的代码为:

function glowShape(r, g, b, type, ...)
  love.graphics.setColor(r, g, b, 15)
  
  for i = 7, 2, -1 do
    if i == 2 then
      i = 1
      love.graphics.setColor(r, g, b, 255)    
    end
    
    love.graphics.setLineWidth(i)
    
    if type == "line" then
      love.graphics[type](...)
    else
      love.graphics[type]("line", ...)
    end
  end
end

function love.draw()
  glowShape(255, 0, 0, "rectangle", 200, 100, 100, 100)
  glowShape(0, 255, 0, "polygon", 300, 300, 310, 330, 350, 290, 360, 310, 290, 350)
end
posted @ 2013-03-16 22:24  半山th  阅读(655)  评论(0编辑  收藏  举报