• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
vipar

Jittery Movement and Uncontrollable Rotating

20 posts in this topic

So I've been looking around to try and figure out how I make my sprite face my mouse. So far the sprite moves to where my mouse is by some vector math.
 
Now I'd like it to rotate and face the mouse as it moves. From what I've found this calculation seems to be what keeps reappearing:
 
    Sprite Rotation = Atan2(Direction Vectors Y Position, Direction Vectors X Position)
 
I express it like so:
 
    sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X);
 
If I just go with the above, the sprite seems to jitter left and right ever so slightly but never rotate out of that position. Seeing as `Atan2` returns the rotation in radians I found another piece of calculation to add to the above which turns it into degrees:
 
    sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / PI;
 
Now I've added + 90 to the above calculation so that it reads:
 
sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / PI + 90;
 
It will now face the mouse correctly every time. (This is different since the video was made)
 
Now the sprite rotates. Problem is that it spins uncontrollably the closer it comes to the mouse. One of the problems with the above calculation is that it assumes that **+y** goes up rather than down on the screen. As I recorded in these two videos, the first part is the slightly jittery movement (A lot more visible when not recording) and then with the added rotation:
 
http://www.youtube.com/watch?v=qOeNWDYiYVw
 
So my questions are:
 
 1. How do I fix that weird Jittery movement when the sprite stands
    still? Some have suggested to make some kind of "snap" where I set
    the position of the sprite directly to the mouse position when it's
    really close. But no matter what I do the snapping is noticeable.
 2. How do I make the sprite stop spinning uncontrollably?
 
The code is as follows:
 
0

Share this post


Link to post
Share on other sites
Think about it. When the mouse point is equal to the rotation point, exactly what orientation should the sprite have? A better way to look at it is this: Imagine a point in the exact center of your body. Now, orient yourself to face that point. The results from atan2 at this point are undefined. Edited by MarkS
1

Share this post


Link to post
Share on other sites

Dunno what Atan2 returns for 0, 0 in Java (EDIT: C# even ;)). In C/C++ it returns 0 and sets errno I think. You have to set it to some value, usually the last valid rotation is the best. Better still is to restrict the cursor so it can't get too close to the rotation centre.

Edited by Paradigm Shifter
0

Share this post


Link to post
Share on other sites

I've tried to stop the sprite when it was very close to the cursor to make it stop rotating like that. I know what is causing it. I just don't know how to really fix it.

0

Share this post


Link to post
Share on other sites
Keep track of the mouse position. If the new mouse position is viable, save it and use it to determine the rotation. If it is not viable, discard it and use the stored position to determine rotation. Edited by MarkS
0

Share this post


Link to post
Share on other sites

Keep track of the mouse position. If the new mouse position is viable, save it and use it to determine the rotation. If it is not viable, discard it and use the stored position to determine rotation.

 

I don't think you read the post or the code :/

I am already doing that.

0

Share this post


Link to post
Share on other sites

Keep track of the mouse position. If the new mouse position is viable, save it and use it to determine the rotation. If it is not viable, discard it and use the stored position to determine rotation.

 
I don't think you read the post or the code :/
I am already doing that.


No, you are tracking the rotation. Track the mouse position.

if fabs(old_pos - mouse_pos) > epsilon then
old_pos = mouse_pos
directionV = Normalize(mouse_pos- sp.Position);
else
directionV = Normalize(old_pos- sp.Position);
endif

newRot = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / (float)Math.PI + 90;
Edited by MarkS
1

Share this post


Link to post
Share on other sites

 

 

Keep track of the mouse position. If the new mouse position is viable, save it and use it to determine the rotation. If it is not viable, discard it and use the stored position to determine rotation.

 
I don't think you read the post or the code :/
I am already doing that.

 


No, you are tracking the rotation. Track the mouse position.

if fabs(old_pos - mouse_pos) > epsilon then
old_pos = mouse_pos
directionV = Normalize(mouse_pos- sp.Position);
else
directionV = Normalize(old_pos- sp.Position);
endif

newRot = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / (float)Math.PI + 90;

 

Can't really see how I should translate this into C# given a mouse position is given by a Vector2i and a position is given by a Vector2f and by subtracting them you can't get a single number you can compare to Epsilon. Epsilon would have to be either  vector itself to test for "is greater than" or the subtractions of the vectors have to be made into a number.

0

Share this post


Link to post
Share on other sites
That is just pseudo-code. Find the distance between the two points and compare the distance to epsilon.
 
distance = sqrt(((old_pos.x - mouse_pos.x) * (old_pos.x - mouse_pos.x)) + ((old_pos.y - mouse_pos.y) * (old_pos.y - mouse_pos.y)));
if fabs(distance) > epsilon then
...
Edited by MarkS
0

Share this post


Link to post
Share on other sites

Yeah, you meant "length" or "magnitude" rather than fabs.

 

And you want to use the square of the distance in your new example (rather than call sqrt, for efficiency reasons) and compare it to epsilon * epsilon, since if a >= 0 and b >= 0 then a >= b if and only if a2 >= b2

Edited by Paradigm Shifter
1

Share this post


Link to post
Share on other sites

That is just pseudo-code. Find the distance between the two points and compare the distance to epsilon.
 

distance = sqrt(((old_pos.x - mouse_pos.x) * (old_pos.x - mouse_pos.x)) + ((old_pos.y - mouse_pos.y) * (old_pos.y - mouse_pos.y)));
if fabs(distance) > epsilon then
...

 

It ended up like this:

 

        private static void MoveSprite(Vector2i mousepos)
        {
            double distance = Math.Sqrt(((sp.Position.X - mousepos.X) * (sp.Position.X - mousepos.X)) + ((sp.Position.Y - mousepos.Y) * (sp.Position.Y - mousepos.Y)));
            if (Math.Abs(distance) > Math.E)
            {
                Vector2f targetV = new Vector2f(mousepos.X, mousepos.Y);
                Vector2f directionV = Normalize(targetV - sp.Position);
                sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / (float)Math.PI + 90;
                sp.Position += directionV * speed;
            }
 
        }
 
It now stops moving when it gets close to the mouse. But it started lagging now. Which I think is somehow related to the Math.Sqrt() call.
0

Share this post


Link to post
Share on other sites

My guess is that Math.E is teeny weeny and not the value you want to test against. You want a buffer of at least a few pixels each side of the centre of rotation. Is it the floating point epsilon? You are testing distance in pixels and my guess is the epsilon is something like 10 to the minus 6? (It's either gonna be the floating point epsilon, usually around 10-6, or else it is exp(1), the base of natural logarithms, which is about 2.718? neither of which would be correct for your purposes). EDIT: I think it is probably Exp(1), i.e. the constant e, which is 2.7 ish, so you are testing whether the mouse is within 2.7 pixels of the centre, probably not enough.

 

And there's no reason to call Sqrt, test the length squared against the distance (what you call epsilon) squared. The distance is the number of pixels you want the dead zone around the centre of rotation to be.

Edited by Paradigm Shifter
1

Share this post


Link to post
Share on other sites

My guess is that Math.E is teeny weeny and not the value you want to test against. You want a buffer of at least a few pixels each side of the centre of rotation. Is it the floating point epsilon? You are testing distance in pixels and my guess is the epsilon is something like 10 to the minus 6? (It's either gonna be the floating point epsilon, usually around 10-6, or else it is exp(1), the base of natural logarithms, which is about 2.718? neither of which would be correct for your purposes). EDIT: I think it is probably Exp(1), i.e. the constant e, which is 2.7 ish, so you are testing whether the mouse is within 2.7 pixels of the centre, probably not enough.

 

And there's no reason to call Sqrt, test the length squared against the distance (what you call epsilon) squared. The distance is the number of pixels you want the dead zone around the centre of rotation to be.

 

I moved the Sqrt() call out of the distance call and squarred epsilon instead. The behaviour is the same except for the lag which is gone now. Thanks. This thread have been helpful.

0

Share this post


Link to post
Share on other sites
No, this is what I meant. Still, I do agree with Paradigm Shifter on the square root.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML.Graphics;
using SFML.Window;

namespace ComponentEngine
{
    class Program
    {
        static RenderWindow window;
        static Sprite sp;
        static Vector2i currentMousePos,old_pos;
        static float speed;

        static void Main(string[] args)
        {
            INIParser iniparser = new INIParser();
            Dictionary<String, int> VideoSettings = iniparser.ParseINI();
            window = new RenderWindow(new VideoMode((uint)VideoSettings["width"], (uint)VideoSettings["height"], 32), "Component Engine");

            sp = new Sprite(new Texture("car.png"));

            Vector2f pos = new Vector2f();
            pos.X = window.Size.X / 2;
            pos.Y = window.Size.Y / 2;
            sp.Position = pos;
            sp.Origin = new Vector2f(sp.Texture.Size.X / 2, 0);
            currentMousePos = new Vector2i((int)window.Size.X / 2, (int)window.Size.Y / 2);
            speed = 1.0f;
            old_pos.X = 0.0f;
            old_pos.Y = 0.0f;
            while (window.IsOpen())
            {
                if (Keyboard.IsKeyPressed(Keyboard.Key.Escape))
                    window.Close();
                currentMousePos = window.InternalGetMousePosition();
                window.DispatchEvents();
                window.Clear();
                MoveSprite(currentMousePos);
                window.Draw(sp);
                window.Display();
            }
        }

        private static void MoveSprite(Vector2i mousepos)
        {
            Vector2f targetV = new Vector2f(mousepos.X, mousepos.Y);
            Vector2f directionV = new Vector2f(0.0f,0.0f);

            float distance = Math.Sqrt(((old_pos.X - mousepos.X) * (old_pos.X - mousepos.X)) + ((old_pos.Y - mousepos.Y) * (old_pos.Y - mousepos.Y)));

            // *NOTE* "epsilon" should be a value that you choose through testing. Find the value that works best.
            if(Math.Abs(distance) > epsilon)
            {
                old_pos = targetV;
                directionV = Normalize(targetV - sp.Position);
            }else{
                directionV = Normalize(old_pos - sp.Position);
            }

            sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / (float)Math.PI + 90;

            Console.WriteLine((mousepos.X - sp.Position.X) + "," + (mousepos.Y - sp.Position.Y));
            sp.Position += directionV * speed;
        }

        private static Vector2f Normalize(Vector2f v1)
        {
            float length = (float)Math.Sqrt((v1.X * v1.X) + (v1.Y * v1.Y));
            float x = v1.X / length;
            float y = v1.Y / length;
            return new Vector2f(x, y);
        }
    }
}
Edited by MarkS
0

Share this post


Link to post
Share on other sites

Also, you don't need to normalize the argument vector to Atan2, it just divides them anyway and calls Atan(y/x) behind the scenes, so Atan2(k * y, k * x) is going to give the same answer as Atan2(y, x)

Edited by Paradigm Shifter
0

Share this post


Link to post
Share on other sites

Did a bit of adjusting and stuff so that I move according to WASD.

 

 

Here is the result of your help :3

 

[media]http://www.youtube.com/watch?v=e0_XTB6y8WE[/media]

Edited by vipar
1

Share this post


Link to post
Share on other sites

Yup, that looks good, nice one!

 

EDIT: Bites lip about you using degrees instead of radians and adding 90 degrees on to your angles instead of measuring them anticlockwise from the +X axis ;)

Edited by Paradigm Shifter
0

Share this post


Link to post
Share on other sites

Yup, that looks good, nice one!

 

EDIT: Bites lip about you using degrees instead of radians and adding 90 degrees on to your angles instead of measuring them anticlockwise from the +X axis ;)

 

I guess I'll see if it comes back and bite me in the ass later Lol

0

Share this post


Link to post
Share on other sites

It won't, but it's just easier working in the correct units for the functions, which in the case of angles is radians, since that makes the maths easier. You aren't gonna measure the speed of your car in furlongs per fortnight are you? As soon as you start doing calculus you should forget about degrees entirely. The only other sensible option is wangs, wide angles, which are like wchars but have 65536 wangs in a full circle instead of 2pi radians, since they play nice with integer overflow on computers ;)

 

[note: I just made up wangs but I like it as a terminology ;)]

 

And if you are asked to draw a right angled triangle with an angle of 45 degrees, you measure the angle anticlockwise from the x axis don't you? That's how all the trig functions are defined. I have no idea why computer scientists like measuring their angles clockwise from due North myself, maybe they want to be sailors?

0

Share this post


Link to post
Share on other sites

It won't, but it's just easier working in the correct units for the functions, which in the case of angles is radians, since that makes the maths easier. You aren't gonna measure the speed of your car in furlongs per fortnight are you? As soon as you start doing calculus you should forget about degrees entirely. The only other sensible option is wangs, wide angles, which are like wchars but have 65536 wangs in a full circle instead of 2pi radians, since they play nice with integer overflow on computers ;)

 

[note: I just made up wangs but I like it as a terminology ;)]

 

And if you are asked to draw a right angled triangle with an angle of 45 degrees, you measure the angle anticlockwise from the x axis don't you? That's how all the trig functions are defined. I have no idea why computer scientists like measuring their angles clockwise from due North myself, maybe they want to be sailors?

 

Given that a Vectors Rotation is calculated in Degrees (which is how they are defined in SFML [0, 360]) I have to calculate in degrees tongue.png

 

It's not a choice.

Edited by vipar
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0