Howdy, Stranger!

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

In this Discussion

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. :)

Sign In or Register to comment.