Hello, I’m new to Codea and found it very accessible, but I have been stuck for days with a touch issue. I have set up a d-pad interface with other buttons for shoot/dash/etc and I’m having trouble understanding how to make a button press-able while holding a direction and vice versa. It seems that “touch” is the only built in variable, so how do you differentiate between one touch being held and another touch beginning - or 2 touches beginning at the same time?
@n0ogit The touch function also uses a touch id. Each time you touch the screen, you get a different id. By using the id, you can differentiate between multiple touches. If you need an example, I have one someplace, I just have to find it.
@n0ogit I found it. You can hold down any one of the direction keys and press the shoot button.
function setup()
rectMode(CENTER)
dir=""
stab=""
btn={}
table.insert(btn,buttons(300,300,100,50,"UP"))
table.insert(btn,buttons(300,100,100,50,"DOWN"))
table.insert(btn,buttons(200,200,100,50,"LEFT"))
table.insert(btn,buttons(400,200,100,50,"RIGHT"))
table.insert(btn,buttons(300,400,100,50,"SHOOT"))
end
function draw()
background(40, 40, 50)
for a,b in pairs(btn) do
b:draw()
if b.pressed then
if b.text=="SHOOT" then
stab=b.text
elseif dir=="" then
dir=b.text
end
end
end
fill(255)
text(dir,WIDTH/2,HEIGHT-50)
text(stab,WIDTH/2,HEIGHT-100)
end
function touched(t)
for a,b in pairs(btn) do
b:touched(t)
end
end
buttons=class()
function buttons:init(x,y,w,h,txt)
self.x=x
self.y=y
self.w=w
self.h=h
self.text=txt
self.left=x-w/2
self.right=x+w/2
self.bottom=y-h/2
self.top=y+h/2
self.pressed=false
self.id=0
end
function buttons:draw()
fill(255)
if self.pressed then
fill(255, 158, 0, 255)
end
rect(self.x,self.y,self.w,self.h)
fill(255,0,0)
text(self.text,self.x,self.y)
end
function buttons:touched(t)
if t.state==BEGAN or t.state==MOVING and self.id==0 then
if t.x>self.left and t.x<self.right and
t.y>self.bottom and t.y<self.top then
self.pressed=true
self.id=t.id
end
end
if t.state==MOVING and self.id==t.id then
if t.x>self.left and t.x<self.right and
t.y>self.bottom and t.y<self.top then
self.pressed=true
else
self.pressed=false
self.id=0
dir=""
stab=""
end
end
if t.state==ENDED and self.id==t.id then
self.pressed=false
self.id=0
dir=""
stab=""
end
end
There are also a couple of sample projects which have examples of handling multiple touches. In my projects, I use a touch handler which gathers the touch information and then delegates it out to various objects that want to use the touch information. You can find my code on github. I’m not particularly recommending you use my code as-is, but it might show you a way to work with multiple touches.
Thank you! That makes complete sense.