Howdy, Stranger!

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

Detecting if a sprite is touched

edited June 2012 in General Posts: 9

I'm working on a simple game as I learn Codea. I'm placing a random number of sprites on the screen. When a sprite is touched, I want it to disappear. I'm looking for a simple way to detect if a sprite is touched. Currently, it looks like I need to write a lot of conditional code. Is there and easy way to handle this in Codea?

Tagged:

Comments

  • edited June 2012 Posts: 50

    Create a class for the sprites with its own touched method that checks the bounding box of the sprite. The bounding box can be determined by the size of the sprite. For example this code drags a vehicle when touched:

    Vehicle = class()
    
    function Vehicle:init(startVec)
        -- you can accept and set parameters here
        self.pos = startVec
        self.height = 70
        self.width = 100
    end
    
    function Vehicle:draw()
        spriteMode(CENTER)
        sprite("SpaceCute:Health Heart", self.pos.x, self.pos.y,100)
    end
    
    function Vehicle:hit(point)
        if point.x > (self.pos.x - self.width) and
           point.x < (self.pos.x + self.width) and
           point.y > (self.pos.y - self.height) and
           point.y < (self.pos.y + self.height) then
            return true
        end        
        return false
    end
    
    function Vehicle:touched(road, touch)
        if self:hit( vec2(touch.x, touch.y) ) and
         touch.state == MOVING then
            self.pos = self.pos + vec2( touch.deltaX, touch.deltaY )
        end
    end
    
  • Posts: 9

    Doffer,

    Thanks for the reply. Very helpful. Got my code working now thanks to your help. :)

  • Can I use this? Will give credit!

  • dave1707dave1707 Mod
    Posts: 8,624

    @DJMoffinz Heres a version if you don’t want to use a class. Use this for whatever you want.

    displayMode(FULLSCREEN)
    
    function setup()  
        fill(255)
        sp=readImage(asset.builtin.Space_Art.Icon)
        spw2=sp.width/2     -- sprite width / 2
        sph2=sp.height/2    -- sprite height / 2
        spx=WIDTH/2         -- sprite x position
        spy=HEIGHT/2        -- sprite y position
    end
    
    function draw()
        background(0)
        sprite(sp,spx,spy)
        if hit then
            text("sprite touched",WIDTH/2,HEIGHT/2+200)
        end
        text("touch or slide your finger on/off the sprite",WIDTH/2,HEIGHT-50)
    end
    
    function touched(t)
        if t.state==BEGAN or t.state==CHANGED then
            if t.x>spx-spw2 and t.x<spx+spw2 and t.y>spy-sph2 and t.y<spy+sph2 then
                hit=true
            else
                hit=false
            end
        end
        if t.state==ENDED then
            hit=false
        end
    end
    
  • Thanks!

Sign In or Register to comment.