Hello,
I’m trying to draw pixels to positon of mouse only, but in my code are pixels drawed next to mouse postion. I suspect the mistake is somewhere here and I would like to understand it.
local index = (y * self.width * 4) + (x * 4) + 1
Can someone explain it to me please?
I’ll send you the whole code to be sure.
local function draw_pixel(self, x, y, r, g, b, a)
-- draw the pixel at the correct index in the buffer stream
local index = (y * self.width * 4) + (x * 4) + 1
print(index)
self.stream[index + 0] = r
self.stream[index + 1] = g
self.stream[index + 2] = b
self.stream[index + 3] = a or 0xff
end
function init(self)
msg.post(".", "acquire_input_focus")
-- size of texture when scaled to nearest power of two
self.width = 960
self.height = 640
-- create RGBA buffer and get the stream so we can manipulate it using Lua
self.buffer = buffer.create(self.width * self.height, { {name=hash("rgba"), type=buffer.VALUE_TYPE_UINT8, count=4} } )
self.stream = buffer.get_stream(self.buffer, hash("rgba"))
-- drawing params
self.color = vmath.vector4(1, 1, 1, 1)
end
function update(self, dt)
local resource_path = go.get("#sprite", "texture0")
local header = { width = self.width, height = self.height, type = resource.TEXTURE_TYPE_2D, format = resource.TEXTURE_FORMAT_RGBA, num_mip_maps = 1 }
resource.set_texture( resource_path, header, self.buffer )
end
function on_input(self, action_id, action)
local pos = vmath.vector3(action.x, action.y, 0)
local x = math.floor(pos.x)
local y = math.floor(pos.y)
r = math.floor(self.color.x * 255)
g = math.floor(self.color.y * 255)
b = math.floor(self.color.z * 255)
a = math.floor(self.color.w * 255)
draw_pixel(self, x, y, r, g, b, a)
end