Search code examples
jqueryspritely

Change spState when direction change in spRandom


another swimming fish question ;-)

Is there a way to detect the direction in which spRandom is currently moving ? So that I can change the spState of my sprite from 1 to 2.

if direction=left spState(1) -> Fish faces left if direction=right spState(2) -> Fish faces right

Hope you understand my question. I did not post any example code yet. Hope anyone can give me a generic example of how to do that.

Thanks and greetz, Arno.


Solution

  • You can always get the position of the element:

       $('#bird').position().top // left, right, bottom.
    

    Then you can get the distance of that this sprite have with the object and set the correct spState.

    Something like:

      distance = Math.sqrt((
                 Math.pow(
                      (object.position().left - spirte.position().left), 2) +
                 Math.pow(
                      (object.position().top - spirte.position().left), 2) 
               ));
    

    So you can check with an if how much distance those things need to have to changue.

    Check this.

    And for watch the sprite you need something like this, is a jQuery plugin that uses Mutations Events for watch the elements, the documentation.

    Also now there's the Mutation Observers is a replace for the Mutations Events, so you can write an observer for your DOM object, more here

    Here's an example i hope it helps you make an idea.

    Update

    All you need to do is get the center of the parent, then check for the current position of your sprite and see if it's more or less than the center.

    Left or Rigth

    Update 2

    It seems to work outside jsfiddle. Test it here. (jsbin)