Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion

Touches break Craft?

in Questions Posts: 1,547

So, maybe I’m late to the party on this, but it seems like if I add a touched(touch) function to a Craft project then nothing else in the project detects touches? For instance, the orbitViewer no longer works…

Tagged:

Comments

  • dave1707dave1707 Mod
    edited November 1 Posts: 9,725

    @UberGoober That’s because when you add the touched function in your code, it overrides the touched function in Craft. I have an example somewhere that allows you to do it. I’ll post the example when I find it.

    Here’s the example. The important code is the addHandler in the btn1:init function. You can set a priority to your touch. When you touch the green box where the red box is behind it, since the red box has a higher priority, then it registers the touch, not the green box.

    viewer.mode=FULLSCREEN
    
    function setup()
        col={{name="red",c=color(255,0,0)},{name="green",c=color(0,255,0)}}
        assert(OrbitViewer, "Please include Cameras (not Camera) as a dependency")
        scene = craft.scene()
        v=scene.camera:add(OrbitViewer, vec3(0,0,0), 100, 0, 200)
        c=scene:entity()
        c.model = craft.model.cube(vec3(25,10,10))
        c.material = craft.material(asset.builtin.Materials.Standard)
        c.material.map = readImage(asset.builtin.Blocks.Trunk_White_Top)
        b1=btn1(300,100,200,150,-2,col[1].name,col[1].c)
        b2=btn1(400,25,200,150,-1,col[2].name,col[2].c)
        str="Press a button or rotate the box"
    end
    
    function draw()
        update(DeltaTime)
        scene:draw()  
        fill(255)  
        text("Drag your finger on the screen to rotate the box",WIDTH/2,HEIGHT-100)
        text(str,WIDTH/2,HEIGHT-200)
        b1:draw()
        b2:draw()
    end
    
    function update(dt)
        scene:update(dt)
    end
    
    btn1 = class()
    
    function btn1:init(x,y,w,h,p,n,c)
        self.x=x
        self.y=y
        self.w=w
        self.h=h
        self.name=n
        self.col=c
        touches.addHandler(self,p)     -- register class with priority
    end
    
    function btn1:draw()
        fill(self.col)
        rect(self.x,self.y,self.w,self.h)    
    end
    
    function btn1:touched(t)
        if t.state == BEGAN then
            if t.x>self.x and t.x<self.x+self.w and
                    t.y>self.y and t.y<self.y+self.h then
                str=self.name.." button pressed"
                return true
            end
        elseif t.state==ENDED then
            str="Press a button or rotate the box"
        end
    end
    
Sign In or Register to comment.