I’m using LibGDX (And this might actually be the problem, considering the top left of the screen is 0, 0 intead of the bottom right, however I have tried subtracting the MouseY from the Height of the application, this didn’t work.
What I’m trying to do: I have a sprite on the screen that I want to rotate towards my mouse at all times.
Here’s the thread I used to try to solve my problem http://www.java-gaming.org/topics/solved-rotation-following-mouse/24763/view
Here’s my code.
package com.chris.spaceshooter.entities;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
public class Player extends Entity
{
// The player Sprite
private Sprite playerSprite;
// The players movement speed
private float playerSpeed = 2.0f;
public Player(Texture texture)
{
this.playerSprite = new Sprite(texture);
this.currSpeed = playerSpeed;
}
public void render(SpriteBatch batch)
{
playerSprite.draw(batch);
}
public void update()
{
if(keyPressed(Keys.W)) { moveUp(); }
if(keyPressed(Keys.A)) { moveLeft(); }
if(keyPressed(Keys.S)) { moveDown(); }
if(keyPressed(Keys.D)) { moveRight(); }
float radiansToMouse = (float) Math.atan2(spriteCenter(playerSprite).y - Gdx.input.getY(), spriteCenter(playerSprite).x - Gdx.input.getX());
float degreesToMouse = 57.2957795f*radiansToMouse;
//Update the sprite position to the Entity position
playerSprite.setX(getX());
playerSprite.setY(getY());
playerSprite.setRotation(degreesToMouse);
}
// Boolean to check if a key is pressed
private boolean keyPressed(int keycode) { return Gdx.input.isKeyPressed(keycode); }
private Vector2 spriteCenter(Sprite sprite) {
float height = sprite.getHeight();
float width = sprite.getWidth();
return new Vector2(width / 2, height / 2);
}
}
This just doesn’t rotate properly and I can’t figure it out! It’s making my balls snarl. Literally.
I have attatched the jar file with my single sprite in a zip file below, so if you can figure anything out, let me know. If any further information is required, please, ask and you shall recieve.
FileSize: 5.1Mb (I guess this is because of LibGDX)
Download: http://up.ht/Jc6XKx