Why does h2d.Object use Math.sin when moving the y axis


#1

Hello!

I am a hobbyist that picked up Heaps in order to learn something new (and hopefully to make a game from); but, as I have bee messing around and learning the 2d framework I noticed that the h2d.Object class had this function

/**
	Move the object by the specied amount along its current direction (rotation angle).
**/
public function move( dx : Float, dy : Float ) {
	x += dx * Math.cos(rotation);
	y += dy * Math.sin(rotation);
}

I extend the Object class to a parent grid class with blocks of tiles; but they can only move on the x axis since my rotation is 0.

I am curious as to why it requires a rotation to move across the y axis?

Thanks!


#2

I mean, I can obviously override my own. I just feel as though I am using this incorrectly


#3

The method documentation provides some insight:

Move the object by the specied amount along its current direction 

So it takes into account the rotation of the object. If you rotate it 90 degrees, then right becomes up (relative to the object).


#4

Thanks for the response alexpana. I get that, but; I guess to me it seems if you have no rotation you would still want to move across the y axis. I thought maybe I was incorrectly using the Object class…

Seems like this would be better no?

/**
    Move the object by the specified amount.
    If rotation is defined shift based on its value
**/
public function move( dx : Float, dy : Float ) {
    if (rotation != 0) {
        dx = dx * Math.cos(rotation);
        dy = dy * Math.sin(rotation);
    }
    x += dx;
    y += dy;
}

Then it would handle both implementations. I wanted to get some feedback before opening a PR, 'cause like I said I am new to this and thought maybe I was missing something.

EDIT: Fixed formatting


#5

There are two issues with your proposal:

  1. Equality comparison with floating point numbers is very error prone due to rounding errors.
  2. Branches negatively affect performance.

You can find more about these topics by searching online. There’s also a rather famous StackOverflow question regarding no 2: https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array

It’s true that if the condition always resolves to the same branch (as is your case) you benefit from branch prediction. But the framework is built for the general case. For any kind of optimization, I can only advise you to measure and see if there’s an improvement.


#6

Thanks for the response alex. I guess the part the confuses me the most is if rotation is not set the object will never move across the y axis; so I would assume that it is expected that the sprite will have some sort of rotation against, where (in my particular case) it does not.

So yeah, I’ll leave it be and just override for my case.

Thanks for the discussion