Drawing rectangle and shape-rendered rectangle at mouse position - java

I'm trying to draw a bounding box that follows the mouse and is positioned beneath it but the rectangle doesn't move with it, it moves too fast or too slow and not at the right place.
I've tried getting the mouse coordinates and passing them in to a rectangle, then I draw a rectangle at its position so I can see where it is.
mouseRect is a rectangle drawn at the mouse's position:
mouseRect.set((float)Gdx.input.getX(), (float)Gdx.input.getY(), 32, 32);
This is my render method that is meant to draw a rectangle at mouseRect's position:
shapeRenderer.setProjectionMatrix(cam.combined);
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.BLUE);
shapeRenderer.rect(mouseRect.x, mouseRect.y, mouseRect.width, mouseRect.height);
shapeRenderer.end();
The box does move when the mouse moves but it's far too fast and it's not positioned under the mouse as should be expected (there's a giant offset and seems to be inverted but when I make it negative it still doesn't work).

I think you should read about coordinate systems. The mouse system is y-down and screen dependent, while (if I remember correctly), the camera is y-up, centered, and uses the viewport size.
I would suggest using a Stage with a listener for mouseMoved or touchDragged events, which have stage coordinates. Add an actor drawing a rectangle to the stage. You could then move the actor accordingly. You wouldn't have to handle coordinate system changes.
It could look like this:
Actor rectangleActor = new RectangleActor();
stage.addActor(rectangleActor);
stage.addListener(new InputListener() {
public boolean mouseMoved(InputEvent event, float x, float y) {
rectangleActor.setPosition(event.getStageX(), event.getStageY());
return false;
}
})
See this answer for how to draw a rectangle in an actor.

Related

positioning a sprite in libgdx

I've got a problem to draw a sprite to my project.
I have a map (960x900) divided into tiles (64x64).
As you can see in the picture, when i click on the bottom left corner of the purple square, the position is (0;0), and when I click on the top right corner of purple square, the position is (36;47)
The problem is that the picture of the purple square has a size of 32x32, and when I draw this picture with libgdx on the screen, the size doesn't match.
Another example: the square with black border has a size of 64x64. So if I draw the purple square in front of the black, the purple should be the half (in height and in width) of the black, no?
Does anyone know why libgdx resizes the purple square?
Sprite sprite = new Sprite(new Texture("assets/purpleSquare.png"));
i draw it in a method
public void render(SpriteBatch batch) {
batch.draw(sprite, 0, 0);
}
I don't know why the picture is resized by libgdx.. I have also tried to do
batch.draw(sprite, 0, 0, width, heigth);
To precise the sprite's size but it doesn't work too..
The size on screen bears no direct relation to the size of the original image. When you draw a sprite you provide the SpriteBatch with a position, width, and height in world coordinates. The sprite will be stretched to fit these world coordinates, regardless of the original image size.
When you click the screen, you are clicking in screen coordinates. The relation between screen and world coordinates is determined by the projection matrix that you use with the SpriteBatch. The projection matrix is typically controlled with a Camera or Viewport object, which you can use to convert between the two coordinate systems using the project and unproject methods.
I'm happy to see that after many hours i found a solution, even if i know which is not correct.
I would like some help to understand the problem's origin.
With this parts of code :
public void update(float delta) {
batch.begin();
drawBackground(); // Draw the background
drawButton(); // Draw the play/pause button
batch.end();
drawMap(); // draw a tmx map made with tiled
batch.begin();
if(!world.isInitial()) {
renderMonster(); // method which draw the monster
}
renderTower(); // method which draw the tower's level
batch.end();
}
I don't understand why i have to do "batch.begin()" and "batch.end()" twice.
I dont' understant why with this code, the purple square is resized.
With this code :
public void update(float delta) {
batch.begin();
drawBackground();
drawButton();
batch.end();
drawMap();
------->sb = new SpriteBatch();
sb.begin();
if(!world.isInitial()) {
renderMonster();
}
renderTower();
sb.end();
}
this line that i add fix the bug with the purple square. If i work with two SpriteBatch (because with one, if i reinitialize SpriteBatch in update method, my pause/play button diseapper) and i initialise the second (SpriteBatch sb) in the update method.
It is correct to initialise a SpriteBatch every time i'm passing on the update method ? There's no method with a SpriteBatch to avoid this problem ?

How to rotate sprite via draw method

I have not found answer for this question anywhere, so let's go.
What i expect:
I want to render rocket. Rocket is flying from given start point with evaluated angle. I'm evaluating angle like this:
getVelocity().angle() - 90f
My problem is to calibrate rocket position on top of the rocket. Image below shows how should it work:
In the top picture is how libgdx render not rotated texture region. In the bottom picture is what i expect: I want to move and rotate texture region with given angle to have (x,y) coordinate on the top of rocket.
What i have:
I tired to write method to draw sprite how i expect but i failed. I think it is caused due to fact that i don't understand documentation of this method.
Following manual:
void com.badlogic.gdx.graphics.g2d.SpriteBatch.draw(TextureRegion region, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation)
Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. The rectangle is offset by originX, originY relative to the origin. Scale specifies the scaling factor by which the rectangle should be scaled around originX, originY. Rotation specifies the angle of counter clockwise rotation of the rectangle around originX, originY.
My code:
public static void drawRotatedTex(SpriteBatch pmRenderer, TextureRegion pmTex, float pmPosX, float pmPosY, float pmAngle)
{
pmRenderer.begin();
pmRenderer.draw(
pmTex, pmPosX, pmPosY, -pmTex.getRegionWidth()/2, pmTex.getRegionHeight(), pmTex.getRegionWidth(), pmTex.getRegionHeight(), 1f, 1f, pmAngle);
pmRenderer.end();
}
Results:
It is moment of collision. As we can see coordinates are offset in relation to rocket.
I don't ask about full solution. For me will be sufficient if someone explain me (on drawing or something) like this method works.
EDIT
Moderation suggested that this question is duplicate of:
libgdx: Rotate a texture when drawing it with spritebatch
I read this topic, but it is not my solution. I know how to rotate my sprite by i don't have idea why coordinates of rocket are offset in relation to rocket top.
EDIT
Invocation of my drawRotatedTex from rocket class:
#Override
public void render(Renderer pmRenderer, float pmX, float pmY) {
SpriteBatch lvSpritebatch = pmRenderer.getSpriteBatch();
Sprite lvSprite = null;
if(mIsExploding)
{
if((lvSprite = mExplosion.getTexture()) != null)
{
lvSpritebatch.begin();
lvSpritebatch.draw(lvSprite, pmX + lvSprite.getWidth()/2, pmY - lvSprite.getHeight()/2);
lvSpritebatch.end();
}
}
else
{
lvSprite = mAnimation.getTexture();
RendererTools.drawRotatedTex(lvSpritebatch,lvSprite,pmX,pmY,getVelocity().angle() - 90f);
}
}
It is not very clear what you are asking, if it's only about moving the origin you would not need that much text. Anyway, I will take a shot at it.
If you want to accomplish what you have in your picture you setup your sprite like this:
sprite.setOrigin(s.getWidth()/2, s.getHeight()); //Centers sprite on top of image.
If I now rotate it in the draw method it rotates around the top center.
sprite.rotate(5);
sprite.draw(batch);
Despite being rotated around the center top of itself it remains position remains the same. If I would set the origin far away from the image and rotate it then the image would travel very far but the position remains the same. Still if you would move it's position 10 pixels to the right the image (wherever it may be) will be moved to the right.
Hope this helps.

libgdx coordinate system differences between rendering and touch input

I have a screen (BaseScreen implements the Screen interface) that renders a PNG image. On click of the screen, it moves the character to the position touched (for testing purposes).
public class DrawingSpriteScreen extends BaseScreen {
private Texture _sourceTexture = null;
float x = 0, y = 0;
#Override
public void create() {
_sourceTexture = new Texture(Gdx.files.internal("data/character.png"));
}
.
.
}
During rendering of the screen, if the user touched the screen, I grab the coordinates of the touch, and then use these to render the character image.
#Override
public void render(float delta) {
if (Gdx.input.justTouched()) {
x = Gdx.input.getX();
y = Gdx.input.getY();
}
super.getGame().batch.draw(_sourceTexture, x, y);
}
The issue is the coordinates for drawing the image start from the bottom left position (as noted in the LibGDX Wiki) and the coordinates for the touch input starts from the upper left corner. So the issue I'm having is that I click on the bottom right, it moves the image to the top right. My coordinates may be X 675 Y 13, which on touch would be near the top of the screen. But the character shows at the bottom, since the coordinates start from the bottom left.
Why is what? Why are the coordinate systems reversed? Am I using the wrong objects to determine this?
To detect collision I use camera.unproject(vector3). I set vector3 as:
x = Gdx.input.getX();
y = Gdx.input.getY();
z=0;
Now I pass this vector in camera.unproject(vector3). Use x and y of this vector to draw your character.
You're doing it right. Libgdx generally provides coordinate systems in their "native" format (in this case the native touch screen coordinates, and the default OpenGL coordinates). This doesn't create any consistency but it does mean the library doesn't have to get in between you and everything else. Most OpenGL games use a camera that maps relatively arbitrary "world" coordinates onto the screen, so the world/game coordinates are often very different from screen coordinates (so consistency is impossible). See Changing the Coordinate System in LibGDX (Java)
There are two ways you can work around this. One is transform your touch coordinates. The other is to use a different camera (a different projection).
To fix the touch coordinates, just subtract the y from the screen height. That's a bit of a hack. More generally you want to "unproject" from the screen into the world (see the
Camera.unproject() variations). This is probably the easiest.
Alternatively, to fix the camera see "Changing the Coordinate System in LibGDX (Java)", or this post on the libgdx forum. Basically you define a custom camera, and then set the SpriteBatch to use that instead of the default.:
// Create a full-screen camera:
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// Set it to an orthographic projection with "y down" (the first boolean parameter)
camera.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.update();
// Create a full screen sprite renderer and use the above camera
batch = new SpriteBatch(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.setProjectionMatrix(camera.combined);
While fixing the camera works, it is "swimming upstream" a bit. You'll run into other renderers (ShapeRenderer, the font renderers, etc) that will also default to the "wrong" camera and need to be fixed up.
I had same problem , i simply did this.
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
screenY = (int) (gheight - screenY);
return true;
}
and every time you want to take input from user dont use Gdx.input.getY();
instead use (Gdx.graphics.getHeight()-Gdx.input.getY())
that worked for me.
The link below discusses this problem.
Projects the given coords in world space to screen coordinates.
You need to use the method project(Vector3 worldCoords) in class com.badlogic.gdx.graphics.Camera.
private Camera camera;
............
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Create an instance of the vector and initialize it with the coordinates of the input event handler.
Vector3 worldCoors = new Vector3(screenX, screenY, 0);
Projects the worldCoors given in world space to screen coordinates.
camera.project(worldCoors);
Use projected coordinates.
world.hitPoint((int) worldCoors.x, (int) worldCoors.y);
OnTouch();
return true;
}

Java Slick2d - How to translate mouse coordinates to world coordinates

I am translating in my main class' render. How do I get the mouse position based on the translation?
public void render(GameContainer gc, Graphics g)
throws SlickException
{
float centerX = 800/2;
float centerY = 600/2;
g.translate(centerX, centerY);
g.translate(-player.playerX, -player.playerY);
gen.render(g);
player.render(g);
}
playerX = 800 /2 - sprite.getWidth();
playerY = 600 /2 - sprite.getHeight();
I update the player position on keydown by .2f * delta
Picture to help with explanation
i92.photobucket.com/albums/l22/occ31191/Untitled-4.png
World coordinates = camera position + mouse position
Camera position is calculated/explained in my answer to this question: Slick2D and JBox2D. How to draw
You're making a tile-based game, where each tile seems to have the same size. For this case, you don't need a generalized unprojection.
Imagine the complete map. The viewport shows only a portion of it; somewhere you need to store the (x,y) offets of the viewport into the complete map. Since the mouse coordinates are relative to the viewport, you need to add this offset to the mouse coordinates. Now, you can easily get the tile coordinates by using modulo operations on the shifted mouse coordinates with the tile's width and height.
Effectively, this is a coordinate transformation of window coordinates to tile coordinates.

Image disappear on rotation in Processing

I'm using the Processing language to do a little game, but I'm having trouble with images and rotation. My sprite displays fine if I apply no rotation to it, but it disappears completely if it is rotated. Here's the rotation code:
void display(boolean alternate) {
pushMatrix();
if(!isHead && !isTail && alternate) rotate(radians(180));
rotate(radians(90*direction));
image(snake, x, y, linkSize, linkSize);
popMatrix();
}
When direction is 0, or alternate is true and direction is 2, then the image displays. Otherwise, no image is displayed. I'm not sure if it matters or not, but snake is a .png image with an alpha transparency. The declaration for snake is snake = loadImage("SnakeLink.png");.
You are actually rotating the image from it's origin (top left corner), so it disappears from the screen.
You have to translate to the center of the image, rotate, translate back to it's origin and then display it.
translate(image.width/2, image.height/2);
rotate(radians);
translate(-image.width/2, -image.height/2);

Categories