ksandarusi
ksandarusi

Reputation: 150

XNA Position Change using Math.Sin

I was wondering why my code isn't entirely working.

        int sinval = (int)Math.Sin(gameTime.ElapsedGameTime.TotalSeconds) * 100;
        mSprite.Position += (new Vector2(5 * sinval, 0));

I have this in my update method, and really I just wanted some sort of proof of concept. Anyway, what I wanted it to do was basically just oscillate a little bit on the X-axis. But for some reason, it only adds the sinval once at the beginning so anytime i change one of the values in this code it has a new starting position but that is about it.

I have this in the update method as well.

New Code:

        int sinval = (int) (Math.Sin(gameTime.ElapsedGameTime.TotalSeconds) * 61);
        mSprite.Position += (new Vector2(25 * sinval, 0));

Upvotes: 0

Views: 1204

Answers (2)

SLaks
SLaks

Reputation: 888047

Math.Sin() is always between -1 and 1.
Casting that to int always returns 0.

You want to cast after multiplying it by 100.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503140

You're rounding the result of Math.Sin to an integer. In almost all cases, that will give 0. Math.Sin returns -1 and 1 for -Math.PI/2 and Math.PI/2 respectively... but in all other cases it'll give 0 after rounding towards 0.

Did you mean to round to integer after multiplying by 100?

int sinval = (int) (Math.Sin(gameTime.ElapsedGameTime.TotalSeconds) * 100);

Upvotes: 2

Related Questions