I want to add motion to two sprite objects in single game screen. I mean two sprite object should move(or follow some predefined path) independently in single page or game screen of app using Libgdx. How can I achieve that.
Please help me. If possible please provide some reference code also. Thank you.
you can use scene2d for this purpose.where you can easily move object through actions.
you can follow these links to learn scene2d.
http://www.gamefromscratch.com/post/2013/11/27/LibGDX-Tutorial-9-Scene2D-Part-1.aspx
http://www.gamefromscratch.com/post/2013/12/09/LibGDX-Tutorial-9-Scene2D-Part-2-Actions.aspx
i hope these links will help you.
You can do this:
take two 2DVector objects:
private Vector2 positiononesprite,positiontwosprite;
Sprite sprite_one,sprite_two;
then in your create method do this
positiononesprite = new Vector2(0,0);
positiontwosprite = new Vector2(0,0);
//set your sprite position
sprite_one.setPosition(x,y);//your x and y coordinates
sprite_two.setPosition(x1,y1);//your second sprite postions
positiononesprite.x = sprite_one.getX();
positiononesprite.y = sprite_one.getY();
positiontwosprite.x = sprite_two.getX();
positiontwosprite.y = sprite_two.getY();
/*
then to make them move in a custom direction you can use either
setPosition method or translate method*/
//apply your algorithm on vectors and set or translate your sprites
// in render method define there speed, direction and move them
//for example i did this to move it in a particular direction
pointerposition.x += directionpointer.x * speed;
pointerposition.y += directionpointer.y * speed;
// pointer.setPosition(pointerposition.x, pointerposition.y);
ball.setPosition(pointerposition.x, pointerposition.y);
this is moving my ball in a particular direction
here directionpointer is a direction vector and speed is a float variable and pointerposition is a vector2 object as i declared positiononesprite
Related
I'm pretty new to libGDX and java in general so I've been following a plethora of tutorials. so FEEL FREE TO CORRECT ME AT EVERY TURN! (yes even in code inefficiencies as well!!)
I currently have the issue of rotating all of the sprites of a single type instead of just a single sprite.
I'll show you how I mean:
libGDX sprite rotation issue
Here are the specifics:
There are 3 different size of sprites.
I use a hashmap to store the 3 sprites so I don't have to Sprite sprite = new Sprite(); every time (supposedly it's a heavy task)
I create a sprite by referencing the one from the hashmap(I think?)
PROBLEM: When I tell a specific sprite to rotate, it rotates each other
sprite of its size.
I have a suspicion that I'm rotating the hashmap reference... If that's the right way to say it.
This is the process I've been using:
hashpmap:
final HashMap<String, Sprite> spriteMap = new HashMap<String, Sprite>();
texture atlas:
spriteAtlas = new TextureAtlas("sprites.txt");
fill hashmap with regions from texture atlas:
private void init spriteMap() {
Array<AtlasRegion> regions = spriteAtlas.getRegions();
for (int i = 0; i < regions.size; i++) {
AtlasRegion region = regions.get(i);
Sprite sprite = spriteAtlas.createSprite(region.name);
float width = sprite.getWidth() / SCALE;
float height = sprite.getHeight() / SCALE;
sprite.setSize(width, height);
sprite.setOrigin(0, 0);
sprite.scale(1f);
spriteMap.put(region.name, sprite);
}
}
create sprite "instance" from hashmap:
private void createNewSprite() {
Sprite sprite;
sprite = spriteMap.get(name);
sprite.setPosition(x, y);
sprite.rotate(rotation);
spriteArray.add(sprite);
}
Maybe I'm not actually extrapolating the sprite from the hashmap well enough?
Let me know if you need anything else to figure out this conundrum.
Thank you so much!
You have only created a single sprite for each region name, referencing it multiple times in spriteArray. Create a new one each time:
private void createNewSprite() {
Sprite sprite = new Sprite(spriteMap.get(name)); //creates a new sprite that is a copy of the one in your map.
sprite.setPosition(x, y);
sprite.rotate(rotation);
spriteArray.add(sprite);
}
They are only slightly heavy. Each Sprite instance has an array of 20 floats for the vertex data, which contains redundant UV data for the underlying TextureRegion, and a redundant Color object and Rectangle object. So it is heavier than creating your own class that references all these things without the redundancies.
They are too heavy to be creating and destroying many of them during game play without using pooling.
What would really be heavy is loading new Textures to create your Sprites instead of them all sharing a single Texture instance.
In my opinion Libgdx Sprites are generally not good for game design because they conflate state with drawing too much, aside from the redundancies. They are useful for particles (and maybe UI elements) where the conflation is not really a design issue. In fact, I think these are the only two places Sprites are used internally in Libgdx.
I am currently trying to make a selector box for an RTS game. For this I need to be able to drag the mouse in order to create the selection box, however this can lead to a negative length/width.
In Libgdx is there a way to make rectangle from just using 2 sets of coordinates?
Thanks.
this is a simple idea, if I understand what you want to do:
to create a rectangle you can use this, Rectangle(float x, float y, float width, float height) for more inforamacion you can read it here http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/math/Rectangle.html
this a psuedo code more or less:
create a listener that captures keystrokes, mouse or them as appropriate,
in touchdown catches x, y, and assign a:
yourVariableTouchDown.x = x;
yourVariableTouchDown.y = y;
then when the touchup captures the x is executed, and the point where it makes up touch and assign a:
yourVariableTouchUp.x = x;
yourVariableTouchUp.y = y;
after create the rectagle:
private Rectangle yourRectangle = new Rectangle();
yourRectangle(yourVariableTouchDown.x, yourVariableTouchDown.y,
(yourVariableTouchDown.x - yourVariableTouchUp.x),
(yourVariableTouchDown.y - yourVariableTouchUp.y));
if you want to see it you can use ShapeRenderer:
look this http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/glutils/ShapeRenderer.html
add for test in variable class
private ShapeRenderer sRDebugRectangel = new ShapeRenderer();
add for test in update or draw
sRDebugRectangel.begin(ShapeType.Filled);
sRDebugRectangel.identity();
sRDebugRectangel.rect(yourRectangle.getX(),
yourRectangle.getY(),
yourRectangle.getWidth(),
yourRectangle.getHeight());
sRDebugRectangel.end();
you can look on that listener use:
https://www.google.es/#q=listener+libgdx
P.S: what you say negative, will be a matter of check when touchup is less than touchdown change where the rectangle is created that was just what I happened to you have test it and adjust the variables to create the rectangle now because you can not be created desirably when negative, now I have time to get with it, in fact eh not tested this why I said it was pseudo code, hope you serve, idea
P.S: You can also look at this https://stackoverflow.com/tour
I'm making apong game, in a boolean method in the Paddle class I want to determine if the ball touching any of the two paddles, I'm struggling of finding the proper logic...
here are the variables:
// instance variables
private Screen theScreen;
private MyroRectangle theRectangle;
private int topLeftX;
private int topLeftY;
// constants
private final int HEIGHT = 100; //the paddle's fixed height
private final int WIDTH = 5; //the paddle's fixed width
private final int PIXELS_PER_MOVE = 20; //the number of pixels a paddle can move either up or down in one timestep
here is the method: * this method is just to determine if the ball touch or not it doesn't do anything with bounce the ball back
public boolean isTouching(Ball b)
{
boolean t = false;
if ((theScreen.getWidth()-(b.getX() + b.getRadius())) >= theScreen.getWidth()-theRectangle.getCenterX() )
{
t= true;
}
return t;
also I tried:
if ((b.getX() > theRectangle.getCenterX()/2) && (b.getY() < theRectangle.getCenterY()/2))
==========
** the methods of the ball class that might be needed:
getX()
getY()
getRadius()
==============
** the Rectangle class:
getCenterX()
getCenterY()
===============
** the Screen class:
getWidth()
getHeight()
I just want to determine at least on of the conditions then I can figure out the rest of them.
In my junior year in college I worked on a Collision detection system algorithm for the windows phone. It is hardly perfect but it was EXTREMELY efficient and can be adapted to a majority of games.
The way that it worked was pretty simple. There were two types of objects; Collidable objects (such as enemies or buildings) and Objects that you wish to check for collisions with these collidable objects.
I had this idea when I was going through a data structures class and we spoke about Linked Lists. I thought what if each link was a collidable object that you could stick your game objects that were already created in it. Then as the game objects moved around you would have a lightweight way of checking their locations for collisions. Thus my system was born.
Basically what it comes down to is using
C (or the distance between to points) = SqrRoot(A^2 + B^2) - radius of ball
this formula should look very familiar to you.
You can see the full answer on this question:
Java More Resourceful Collision Detection
This problem can be seen as solving the question if two 2d-areas, the paddle (a rectangle) and the ball (a circle) intersect. You can just google/wiki formulas for that.
If you don't want to go into the math for solving the problem through geometry, package java.awt.geom contains classes that can do the calculations for you, namely java.awt.Area. You would just create Area instances for paddle and ball and then call the intersects() method to know if they collided.
I am trying to re-create Pong using LibGDX and Box2D. I have 2 problems, if I fix one it creates another.
My paddles are currently set to Kinematic and are controlled using the up/down keys via a controller class. This works just fine and I can happily play back and forth.
Problem being, my walls are static bodies and my paddles just travel right through them.
Now I can fix this by simple changing the paddle body to a dynamic one, this stops the paddles from going through the walls but then when my ball strikes off a paddle, it goes flying off the X axis and off the screen.
I have tried adding an update method in my controller class as follows:
public void update(float delta){
paddleBodyPosY = paddleBody.getPosition().x;
paddleBodyPosY = paddleBody.getPosition().y;
System.out.println(paddleBodyPosY);
}
The console reports the paddle position being updated every frame, from top to bottom of screen.
So I went back to my GameScreen class and tried all sorts of code in the Render() method like so:
if(playerOnePaddle.paddleBodyPosY < 0){
playerOnePaddle.paddleBody.getPosition().y = 0;
System.out.println("resetting paddle");
}
I have tried LOADS of variations, I can easily break movement by calling paddleBody.setLinearVelocity(0,0) but then it gets stuck like this and it's not movable anymore. Obviously the problem must lie with the fact that I can't set a position using a getter lol.
Any ideas? If you need more snippets ask, I didn't want to overload the question with 100 lines of code you don't need to see :S.
The paddle creation method:
public void createPaddle(World world, float x, float y){
//Define a body for the paddle
BodyDef paddleBodyDef = new BodyDef();
paddleBodyDef.type = BodyType.KinematicBody;
paddleBodyDef.position.set(x, y);
//Define a shape for the paddle
PolygonShape paddleShape = new PolygonShape();
paddleShape.setAsBox(paddleWidth, paddleHeight);
//Define a fixture for the paddle
FixtureDef paddleFixtureDef = new FixtureDef();
paddleFixtureDef.shape = paddleShape;
paddleFixtureDef.density = 0;
//Ensures ball bounces off paddle
//Consistently without losing velocity
paddleFixtureDef.restitution = 1.005f;
//Create the paddles
paddleBody = world.createBody(paddleBodyDef);
paddleFixture = paddleBody.createFixture(paddleFixtureDef);
paddleShape.dispose();
}
Heh, so what I did was.
Set my paddles to dynamic, then set there mass to a stupidly high number so that the a ball would not move them on the x axis, well not enough for the human eye to see at least.
Seems like a cheap fix, if anyone has anything better...that would be great lol
I'm having a little problem with figuring something out (Obviously).
I'm creating a 2D Top-down mmorpg, and in this game I wish the player to move around a tiled map similar to the way the game Pokemon worked, if anyone has ever played it.
If you have not, picture this: I need to load various areas, constructing them from tiles which contain an image and a location (x, y) and objects (players, items) but the player can only see a portion of it at a time, namely a 20 by 15 tile-wide area, which can be 100s of tiles tall/wide. I want the "camera" to follow the player, keeping him in the center, unless the player reaches the edge of the loaded area.
I don't need code necessarily, just a design plan. I have no idea how to go about this kind of thing.
I was thinking of possibly splitting up the entire loaded area into 10x10 tile pieces, called "Blocks" and loading them, but I'm still not sure how to load pieces off screen and only show them when the player is in range.
The picture should describe it:
Any ideas?
My solution:
The way I solved this problem was through the wonderful world of JScrollPanes and JPanels.
I added a 3x3 block of JPanels inside of a JScrollPane, added a couple scrolling and "goto" methods for centering/moving the JScrollPane around, and voila, I had my camera.
While the answer I chose was a little more generic to people wanting to do 2d camera stuff, the way I did it actually helped me visualize what I was doing a little better since I actually had a physical "Camera" (JScrollPane) to move around my "World" (3x3 Grid of JPanels)
Just thought I would post this here in case anyone was googling for an answer and this came up. :)
For a 2D game, it's quite easy to figure out which tiles fall within a view rectangle, if the tiles are rectangular. Basically, picture a "viewport" rectangle inside the larger world rectangle. By dividing the view offsets by the tile sizes you can easily determine the starting tile, and then just render the tiles in that fit inside the view.
First off, you're working in three coordinate systems: view, world, and map. The view coordinates are essentially mouse offsets from the upper left corner of the view. World coordinates are pixels distances from the upper left corner of tile 0, 0. I'm assuming your world starts in the upper left corner. And map cooridnates are x, y indices into the map array.
You'll need to convert between these in order to do "fancy" things like scrolling, figuring out which tile is under the mouse, and drawing world objects at the correct coordinates in the view. So, you'll need some functions to convert between these systems:
// I haven't touched Java in years, but JavaScript should be easy enough to convey the point
var TileWidth = 40,
TileHeight = 40;
function View() {
this.viewOrigin = [0, 0]; // scroll offset
this.viewSize = [600, 400];
this.map = null;
this.worldSize = [0, 0];
}
View.prototype.viewToWorld = function(v, w) {
w[0] = v[0] + this.viewOrigin[0];
w[1] = v[1] + this.viewOrigin[1];
};
View.prototype.worldToMap = function(w, m) {
m[0] = Math.floor(w[0] / TileWidth);
m[1] = Math.floor(w[1] / TileHeight);
}
View.prototype.mapToWorld = function(m, w) {
w[0] = m[0] * TileWidth;
w[1] = m[1] * TileHeight;
};
View.prototype.worldToView = function(w, v) {
v[0] = w[0] - this.viewOrigin[0];
v[1] = w[1] - this.viewOrigin[1];
}
Armed with these functions we can now render the visible portion of the map...
View.prototype.draw = function() {
var mapStartPos = [0, 0],
worldStartPos = [0, 0],
viewStartPos = [0, 0];
mx, my, // map coordinates of current tile
vx, vy; // view coordinates of current tile
this.worldToMap(this.viewOrigin, mapStartPos); // which tile is closest to the view origin?
this.mapToWorld(mapStartPos, worldStartPos); // round world position to tile corner...
this.worldToView(worldStartPos, viewStartPos); // ... and then convert to view coordinates. this allows per-pixel scrolling
mx = mapStartPos[0];
my = mapStartPos[y];
for (vy = viewStartPos[1]; vy < this.viewSize[1]; vy += TileHeight) {
for (vx = viewStartPos[0]; vx < this.viewSize[0]; vy += TileWidth) {
var tile = this.map.get(mx++, my);
this.drawTile(tile, vx, vy);
}
mx = mapStartPos[0];
my++;
vy += TileHeight;
}
};
That should work. I didn't have time to put together a working demo webpage, but I hope you get the idea.
By changing viewOrigin you can scroll around. To get the world, and map coordinates under the mouse, use the viewToWorld and worldToMap functions.
If you're planning on an isometric view i.e. Diablo, then things get considerably trickier.
Good luck!
The way I would do such a thing is to keep a variable called cameraPosition or something. Then, in the draw method of all objects, use cameraPosition to offset the locations of everything.
For example: A rock is at [100,50], while the camera is at [75,75]. This means the rock should be drawn at [25,-25] (the result of [100,50] - [75,75]).
You might have to tweak this a bit to make it work (for example maybe you have to compensate for window size). Note that you should also do a bit of culling - if something wants to be drawn at [2460,-830], you probably don't want to bother drawing it.
One approach is along the lines of double buffering ( Java Double Buffering ) and blitting ( http://download.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html ). There is even a design pattern associated with it ( http://www.javalobby.org/forums/thread.jspa?threadID=16867&tstart=0 ).