Make element change behaviour after .onHit()

27 views
Skip to first unread message

Leszek Kasperczyk

unread,
May 18, 2013, 10:34:35 AM5/18/13
to craf...@googlegroups.com
Hi,

I have green balls elements moving randomly on the screen, which are changing color to red when you click on them. What I want to do is to make the red balls stop moving randomly and make them automatically follow any other green balls and "affect" them with their color and behavior. The red ball should live no longer than 5 seconds and after that time it should disappear.

My component for the balls looks like this:

Crafty.c('Ball', {
  init: function() {
    this.requires('2D, DOM, Color, Mouse, Collision, Shape')

.attr({ x: Math.floor((Math.random()*600)+1), y: Math.floor((Math.random()*300)+1), 
dX: Crafty.math.randomInt(2, 5), 
dY: Crafty.math.randomInt(2, 5) })
.bind('EnterFrame', function () {
//hit floor or roof
if (this.y <= 0 || this.y >= 290)
this.dY *= -1;
if (this.x <= 0 || this.x >= 590)
this.dX *= -1;
this.x += this.dX;
this.y += this.dY;
})
.color('rgb(0,0,255)')
.bind('Click', function() {alert("over")})
.onHit('Ball', function () {
this.dX *= -1;
}
)
.circle(20)
},
  
});


Here are my questions:

1. 'Click' function doesn't work - it works only if I remove the Collision. How can I make it work with collision on?
2. How can I make the Ball to change it's behavior after click and become Red Ball? I know I should I create new component, eg. 'RedBall', but:
   a) I don't know how to change the 'Ball' into 'RedBall' after Click() and onHit(),
   b) I don't know how to make the 'RedBall' follow other balls that are not red.

Thanks in advance!

Steve Byrnes

unread,
May 18, 2013, 10:53:14 AM5/18/13
to craf...@googlegroups.com
> 1. 'Click' function doesn't work - it works only if I remove the Collision.
> How can I make it work with collision on?

See https://github.com/craftyjs/Crafty/issues/448 . The workaround is
that you need to run "this.collision()" AFTER the length and width of
the component have been set (i.e. after this.attr(...) within the
init).

--Steve
~~
Steven Byrnes
http://sjbyrnes.com/
Reply all
Reply to author
Forward
0 new messages