Fix "my" method to make an object A move toward X,Y coordinates

hello,
in order to move my rectangle toward the mouse X & Y coordinate i created this method
and it kinda work but sometimes it gives a strange behavior
so instead of moving like this (O=object, T=target) :

it does something similar to this

i hope you understand what i meant :stuck_out_tongue:

and here is my methode code

// tx and ty are the target coordinates
	public void move(int tx, int ty) {

		// calculate distance to cross
		int xdistance;
		xdistance = tx - x;
		// check if the target point is on the right or on the left
		// go to it
		// decrements/increments the distance so it will reach zero
		// and break the condition
		if (xdistance > 0) {
			x += s;
			xdistance -= s;
		} else if (xdistance < 0) {
			x -= s;
			xdistance += s;
		}

		// same thing
		int ydistance;
		ydistance = ty - y;
		if (ydistance > 0) {
			y += s;
			ydistance -= s;
		} else if (ydistance < 0) {
			y -= s;
			ydistance += s;
		}

	}

thank you

Normalize the direction vector, then multiply it to the speed you want.

sorry but what do you mean by ā€œnormalizeā€ :stuck_out_tongue: ??

Get the length of the vector and then get each component of the vector and divide it by the length.

Here is some code for that using LWJGL’s Vector2f class:

//mouse is point B
Vector2f mouse = new Vector2f(Mouse.getX(), Mouse.getY());

//get direction
Vector2f dir = new Vector2f(mouse.x - x, mouse.y - y);

//normalize it
dir.normalise();

//scale the vector based on our movement speed
float speed = 2f;
dir.scale(speed);

//move the entity with our new direction vector
x += dir.x;
y += dir.y;

If you’re a crazy fool and you’re using Java2D, it might look like this… :stuck_out_tongue:

//mouse is point B
float mx = Mouse.getX();
float my = Mouse.getY();

//get direction
float dx = mx - x;
float dy = my - y;

//normalize it
float len = (float)Math.sqrt(dx * dx + dy * dy);
if (len!=0) {
	dx /= len;
	dy /= len;
}

//scale the vector based on our movement speed
float speed = 2f;
dx *= speed;
dy *= speed;

//move the entity with our new direction vector
x += dx;
y += dy;

You might also need a condition to avoid ā€œflickeringā€ when the entity lies under point B (the mouse).

:o
seriously,
is it that bad :-\ ??
i thought it’s better to start learning without any external library
well i need to finish this very tiny small game and then maybe i start to learn LWJGL
ps :
can you post a link for a nice explained tutorial for LWJGL please ?

thank you

IMHO there is no point in using Java2D for games nowadays, unless you are competing in Java4K.

If you decide to use LWJGL, you need to build everything from the ground up. This can be complicated and daunting for a newbie, for example:
LWJGL ShaderProgram Utility (See my other LWJGL tutorials here)

A better option would be to use a framework like LibGDX. Not only does LibGDX handle all that low-level stuff for you, it also includes utilities like themable GUI, bitmap font generation, integration with Box2D physics, tiled map loading, particle editor tool, texture atlas management, efficient sprite rendering, and much more.

For getting started with LibGDX:
http://libgdx.badlogicgames.com/documentation.html

You can read more about the issue with Java2D for games in this thread:

Start here:
http://www.lwjgl.org/wiki/index.php?title=LWJGL_Basics_1_(The_Display)
http://www.lwjgl.org/wiki/index.php?title=LWJGL_Basics_2_(Input)
http://www.lwjgl.org/wiki/index.php?title=LWJGL_Basics_3_(The_Quad)

Then read the Space Invaders tutorials here (especially 104):
http://www.cokeandcode.com/index.html?page=tutorials

Then you can try making a game with that.
Then forget the rendering methods because immediate mode is useless for performance.

Then this for VBOs (don’t worry about 3D. Just stick to 2D):

Then you can try these:



Be aware that this will be a long process. It will probably take many months to learn all that.
I recommend to mix up 2D and 3D games while you’re at it.
But at least you’ll understand OpenGL properly.
If you want to be lazy and don’t care about understanding, use LibGDX.

[quote]If you want to be lazy and don’t care about understanding, use LibGDX.
[/quote]
This isn’t really valid.

You can learn the OpenGL pipeline with LibGDX. In many places it wraps it very thinly, e.g.

Texture tex = new Texture("data/img.png");
// -> glTexImage2D(...)

tex.setFilter(TextureFilter.Linear, TextureFilter.Linear);
// -> glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// -> glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

tex.drawPixmap(pixels, x, y); 
// -> glTexSubImage2D(x, y, ... pixels);

tex.bind(1);
// -> glActiveTexture(GL_TEXTURE1);
// -> glBindTexture(GL_TEXTURE_2D, texID);

You don’t need to write the verbose OpenGL boilerplate in oder to understand how shaders and textures work.

Same goes for other areas like ShaderProgram, Mesh, etc. Ultimately LibGDX is just another OpenGL wrapper, and you can use it however you choose.

As I explain in my tutorial series, it may be easier to learn shaders and the programmable pipeline by using a high-level API (LibGDX, lwjgl-basics, etc) rather than getting bogged down on OpenGL boilerplate.

Texture tex = new Texture("data/img.png");

There’s a bit more going on in there than just glTexImage2D()

This is my Java2D method.

[icode]moveTo()[/icode]


/**
 * Moves this object to a specified point with a specific speed. Note that
 * the velocity used is independent of vertical or horizontal velocities of
 * this object.
 * 
 * @param nx The new x-position
 * @param ny The new y-position
 * @param speed The speed with which to move
 * @return True if the new point has been reached
 */
public boolean moveTo(float nx, float ny, float speed){
    boolean _x = false;
    boolean _y = false;
    int distance = (int) Math.sqrt((double) ((x - nx) * (x - nx) + (y - ny) * (y - ny)));
    float vel = Math.min(distance, speed);
    float newx = x;
    float newy = y;
    if (x > nx) {
        // We should move left
        newx -= vel;
    } else if (x < nx) {
        // We should move right
        newx += vel;
    } else {
        _x = true;
    }
    if (y > ny) {
        // We should move up
        newy -= vel;
    } else if (y < ny) {
        // We should move down
        newy += vel;
    } else {
        _y = true;
    }
    x = newx;
    y = newy;
    return (_x && _y);
}

Why reinvent the wheel? It’s better for a newbie to use a framework built by people way more talented.

Also, why aren’t you writing in machine code? Or better yet, in binary like a boss?

Your personal preference is calling OpenGL directly, don’t devolve someone else to your level =P

(having said that, I like writing everything myself, I’m working on changing that… it’s hard)

[analogy]
Because if I know how a wheel works, I can fix the car quicker if something goes wrong. I can also make the wheel better for me. And because I know how it works too, I can make a wheel out of different materials, some which may be better than the current. In the end, it’s much better than relying on a one-size-fits-all wheel that goes slow, because despite being on a F1 car, it was also designed with trucks in mind too.
[/analogy]

Also, I want to be one of those ā€œpeople way more talentedā€. And I’m sure there are lots of others out there too. I know this for certain, because if there weren’t, LibGDX or any other library wouldn’t exist today. These people should not be told to just go and download loads of libraries to do things for them. Lazy people will always pick the lazy solution, no matter what you tell them. But talented people need some one to say ā€œit will be good for youā€ before they go into the relatively unknown.

FIFY

The only problem is, that you wouldn’t know how to produce a competing high-tech wheel without looking back on the experience of generations of engineers, using it, learning from it, and then, eventually, if it makes sense, creating your own improved thing.
Using a matured library is not the lazy but the professional way.

Sorry, I accidentally clicked upon Appreciate.

I think the appreciation is deserved.

(Blah blah… I really don’t like the 90% quote thing…)

So uhm… If you aren’t able to create a high tech thing, without looking back at other high tech things, then how did the first high tech things appear? Magic? And yes, using a full fledged library, before learning any basics is surely laziness. And very few on this forum can be called professional game developers.

And I really don’t get the whole argument that you should just use a library to do everything for you. Do you use a library to wipe your own ass too(Mmm, paper jokes)? I completely agree that a library can be helpful. But there never should be a point where someone say ā€œOh, instead of learning how to actually do what you want to do, just use X library, it’ll do everything for you, even make your coffee.ā€

For simple 2d, for beginners, there’s nothing wrong with learning the robes, before taking on a full fledged library. At least encourage people to THINK before telling them that they can achieve world peace, if they use library X. :confused:

And where’s the need to use LWJGL for any of this?

Here’s the same code, using javax.vecmath.Vector2d:


//mouse is point B
Vector2d mouse = new Vector2d(Mouse.getX(), Mouse.getY());

//get direction
Vector2d dir = new Vector2d(mouse.x - x, mouse.y - y);

//normalize it
dir.normalize(); // This time, spelled with a z, instead of an s.

//scale the vector based on our movement speed
float speed = 2f;
dir.scale(speed);

//move the entity with our new direction vector
x += dir.x;
y += dir.y;

And Mouse.getX() / Mouse.getY() could be taken from my own MouseController class.

Teach people to learn some basic stuff, before teaching them to use a library, and please for the love of <whatever you think is epic/awesome/holy/etc>, do NOT involve new people in your wars of what library is the most epic. It’s just a waste of time.

@alaslipknot
Do a few basic Java2d games, before moving to a big fat library(The joke here is, that most of what’s shipped with Java is already libraries, which is why there’s the whole throwing around of ā€œwhy not write machine code then, if you don’t want to use a library, blablablaā€).

Just get a feel for how things work and how to structure your stuff. Once’s you’ve gotten down sprites, etc. etc., then you can start learning OpenGL and one of the many libraries out there(Of which most use LWJGL internally, as far as I’ve seen…).

Cheers and good luck! :slight_smile:

if(threadDerailed){
http://i.imgur.com/VKaWX.gif
}

Seriously though, OpenGL is not like learning to fingerpaint. It’s vector math, and C, and NDC/camera Space/Clip Space/world space…
Methinks that Java2D sounds fun and informative.

yes i agree with that, but, wouldn’t be a wrong i started since the 1st game with LWJGL ??
i mean Java2D is the basics no ?

[quote]If you decide to use LWJGL, you need to build everything from the ground up. This can be complicated and daunting for a newbie,
[/quote]
Exactly, that’s why i think that the good way to start is Java2D, then start to learn LWJGL step by step, it would be easier no ?

[quote]A better option would be to use a framework like LibGDX. Not only does LibGDX handle all that low-level stuff for you, it also includes utilities like themable GUI, bitmap font generation, integration with Box2D physics, tiled map loading, particle editor tool, texture atlas management, efficient sprite rendering, and much more.
[/quote]
I don’t like that, specially if i don’t have the minimum knowledge of basics stuffs, i don’t know why i feel like this about using FrameWork or Engines but using them make me feel like am not intelligent enough (or lazy) to start with basics and reach that level one day, it’s like using a GameMaker but with more advanced script features :stuck_out_tongue:

don’t worry, i will handle that 8)
and nope, LibGDX is my last option for now

@SHC
thank you

then i will be a newbie forever :stuck_out_tongue:
do you want me to be a newbie forever ::slight_smile: ??

OKAY ;D !!

@BrassApparatus
xD
and yeees !! i tried to take a look at few openGl examples, and i was " :o !! "
we’ll understand it one day :wink:

thank you guys very much for your help, i really appreciate that

I guess it depends what your end goals are… if it’s making games for a living… then it’s smart to use libraries. If you are doing it for the learning experience or because you want to make your own library… then go the LWJGL way!