Libgdx resize window on android to fill screen - java

I am trying to fill the resize function that comes with Libgdx to fit all of the android screens.
The best solution I have seen so far is this tutorial: http://www.java-gaming.org/index.php?topic=25685.0 but when I run it on my Galaxy S3 the buttons are really tiny and just overall the whole game is tiny where on the desktop version it is big and the way I want it to be. My resize code right now is:
#Override
public void resize(int width, int height) {
float aspectRatio = (float)width/(float)height;
float scale = 2f;
Vector2 crop = new Vector2(0f, 0f);
if(aspectRatio > ASPECT_RATIO)
{
scale = (float)height/(float)VIRTUAL_HEIGHT;
crop.x = (width - VIRTUAL_WIDTH*scale)/2f;
}
else if(aspectRatio < ASPECT_RATIO)
{
scale = (float)width/(float)VIRTUAL_WIDTH;
crop.y = (height - VIRTUAL_HEIGHT*scale)/2f;
}
else
{
scale = (float)width/(float)VIRTUAL_WIDTH;
}
float w = (float)VIRTUAL_WIDTH*scale;
float h = (float)VIRTUAL_HEIGHT*scale;
viewport = new Rectangle(crop.x, crop.y, w, h);
}
My render code is:
#Override
public void render() {
// update camera
camera.update();
// set viewport
Gdx.gl.glViewport((int) viewport.x, (int) viewport.y,
(int) viewport.width, (int) viewport.height);
// clear previous frame
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
ScreenManager.updateScreen();
sb.begin();
ScreenManager.renderScreen(sb);
sb.end();
}
And my variables are:
private static final int VIRTUAL_WIDTH = 600;
private static final int VIRTUAL_HEIGHT = 800;
private static final float ASPECT_RATIO = (float)VIRTUAL_WIDTH/(float)VIRTUAL_HEIGHT;
public static BitmapFont FONT;
private OrthographicCamera camera;
private Rectangle viewport;
private SpriteBatch sb;
Like I said, when I run the desktop version it works fine but when I run it on my Galaxy S3 (Screen Dim: 1,280 x 720), the game is zoomed out a lot, and it crops out the tops and sides of the game which is not what I want at all.

Related

Android custom view canvas clear fails

I'm writing a simple custom View that should draw the an RSSI signal shape (two overlapping triangles one filled proportionally with the level of the signal). The components works except for the clearing of canvas.
I tought I need to do something like that:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int mWidth = getMeasuredWidth();
final int mHeight = getMeasuredHeight();
final float _fillw = mWidth * (mLevel) / 100f;
final float _fillh = mHeight * (100f - mLevel) / 100f;
//canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.drawColor(Color.BLACK);
if (mLevel < mWarnLevel)
mFillPaint.setColor(mWarnFillColor);
else if ((mLevel >= mWarnLevel) && (mLevel < mSafeLevel))
mFillPaint.setColor(mFillColor);
else if (mLevel >= mSafeLevel)
mFillPaint.setColor(mSafeFillColor);
mFramePath.moveTo(0, mHeight);
mFramePath.lineTo(mWidth, mHeight);
mFramePath.lineTo(mWidth, 0);
mFramePath.close();
mFillPath.moveTo(0, mHeight);
mFillPath.lineTo(_fillw, mHeight);
mFillPath.lineTo(_fillw, _fillh);
mFillPath.close();
canvas.drawPath(mFramePath, mFramePaint);
canvas.drawPath(mFillPath, mFillPaint);
}
public void setLevel(int level) {
if (this.mLevel != level) {
this.mLevel = level;
invalidate();
}
}
The level is drawn correctly until it grows and the triangle area also get larger. When it start to decrease the area is not updated anymore probably beacuse the background is not cleared.
I tried also to use the commented .drawColor() line without luck.
P.S. I need to have a transparent background on this View.
You just have to clear the path
public void clear()
{
mFramePath.reset();
mFillPath.reset();
invalidate();
}

Floating Bitmaps, Coding Conflicts?

Good day, I am beginning to learn Java and one of the first projects that I thought might help me to begin learning is by designing a watch face for WearOS, I am an artist/illustrator (currently going back to school to learn computer programming) by birth and school, so I am currently attempting work that I have some idea about.
My question is this. I have designed and implemented bitmaps that are rotating for the watch's hands, and have tried to center them with "mCenterX and Y" and have even manually tried to center them with canvas.translate, and entering in coordinates. Sorry if this is an absolute newbie question, but I have been Googling and attempting for at least a week. (Would include image of floating hands, but can't embed.)
The "Hour Hand" is the only one that I have currently working, and I only was able to do that with manually entering the coordinates with canvas.translate. The other hands will come into frame every-once-in-a-while then float out of frame, rotating around some "unknown" center point.
Code is below: (I have included all code pertaining to the bitmaps for the hour/minute/second hands, to see if I have something that is conflicting. I am using bits of code from various projects, which probably explains the off-centeredness, but I don't have the knowledge yet to grasp why, which is my ultimate goal here.)
Thank you for looking and replying! If you need additional information, let me know.
private class Engine extends CanvasWatchFaceService.Engine {
private static final float HOUR_STROKE_WIDTH = 5f;
private static final float MINUTE_STROKE_WIDTH = 3f;
private static final float SECOND_TICK_STROKE_WIDTH = 2f;
private static final float CENTER_GAP_AND_CIRCLE_RADIUS = 4f;
private static final int SHADOW_RADIUS = 6;
/* Handler to update the time once a second in interactive mode. */
private final Handler mUpdateTimeHandler = new EngineHandler(this);
private Calendar mCalendar;
private final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mCalendar.setTimeZone(TimeZone.getDefault());
invalidate();
}
};
private boolean mRegisteredTimeZoneReceiver = false;
private boolean mMuteMode;
private float mCenterX;
private float mCenterY;
private int mWatchHandColor;
private int mWatchHandHighlightColor;
private int mWatchHandShadowColor;
private Paint mHourPaint;
private Paint mMinutePaint;
private Paint mSecondPaint;
private Paint mTickAndCirclePaint;
private Paint mBackgroundPaint;
private Bitmap mHourBitmap;
private Bitmap mMinuteBitmap;
private Bitmap mSecondBitmap;
private Bitmap mBackgroundBitmap;
private Bitmap mGrayBackgroundBitmap;
private void initializeWatchFace() {
/* Set defaults for colors */
mWatchHandColor = Color.WHITE;
mWatchHandHighlightColor = Color.RED;
mWatchHandShadowColor = Color.BLACK;
mHourPaint = new Paint();
mHourPaint.setColor(mWatchHandColor);
mHourPaint.setStrokeWidth(HOUR_STROKE_WIDTH);
mHourPaint.setAntiAlias(true);
mHourPaint.setStrokeCap(Paint.Cap.ROUND);
mHourPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
mMinutePaint = new Paint();
mMinutePaint.setColor(mWatchHandColor);
mMinutePaint.setStrokeWidth(MINUTE_STROKE_WIDTH);
mMinutePaint.setAntiAlias(true);
mMinutePaint.setStrokeCap(Paint.Cap.ROUND);
mMinutePaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
mSecondPaint = new Paint();
mSecondPaint.setColor(mWatchHandHighlightColor);
mSecondPaint.setStrokeWidth(SECOND_TICK_STROKE_WIDTH);
mSecondPaint.setAntiAlias(true);
mSecondPaint.setStrokeCap(Paint.Cap.ROUND);
mSecondPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
mTickAndCirclePaint = new Paint();
mTickAndCirclePaint.setColor(mWatchHandColor);
mTickAndCirclePaint.setStrokeWidth(SECOND_TICK_STROKE_WIDTH);
mTickAndCirclePaint.setAntiAlias(true);
mTickAndCirclePaint.setStyle(Paint.Style.STROKE);
mTickAndCirclePaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
}
private void updateWatchHandStyle() {
if (mAmbient) {
mHourPaint.setColor(Color.WHITE);
mMinutePaint.setColor(Color.WHITE);
mSecondPaint.setColor(Color.WHITE);
mTickAndCirclePaint.setColor(Color.WHITE);
mHourPaint.setAntiAlias(false);
mMinutePaint.setAntiAlias(false);
mSecondPaint.setAntiAlias(false);
mTickAndCirclePaint.setAntiAlias(false);
mHourPaint.clearShadowLayer();
mMinutePaint.clearShadowLayer();
mSecondPaint.clearShadowLayer();
mTickAndCirclePaint.clearShadowLayer();
} else {
mHourPaint.setColor(mWatchHandColor);
mMinutePaint.setColor(mWatchHandColor);
mSecondPaint.setColor(mWatchHandHighlightColor);
mTickAndCirclePaint.setColor(mWatchHandColor);
mHourPaint.setAntiAlias(true);
mMinutePaint.setAntiAlias(true);
mSecondPaint.setAntiAlias(true);
mTickAndCirclePaint.setAntiAlias(true);
mHourPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
mMinutePaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
mSecondPaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
mTickAndCirclePaint.setShadowLayer(SHADOW_RADIUS, 0, 0, mWatchHandShadowColor);
}
#Override
public void onInterruptionFilterChanged(int interruptionFilter) {
super.onInterruptionFilterChanged(interruptionFilter);
boolean inMuteMode = (interruptionFilter == WatchFaceService.INTERRUPTION_FILTER_NONE);
/* Dim display in mute mode. */
if (mMuteMode != inMuteMode) {
mMuteMode = inMuteMode;
mHourPaint.setAlpha(inMuteMode ? 100 : 255);
mMinutePaint.setAlpha(inMuteMode ? 100 : 255);
mSecondPaint.setAlpha(inMuteMode ? 80 : 255);
invalidate();
}
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
super.onSurfaceChanged(holder, format, width, height);
/*
* Find the coordinates of the center point on the screen, and ignore the window
* insets, so that, on round watches with a "chin", the watch face is centered on the
* entire screen, not just the usable portion.
*/
mCenterX = width / 2f;
mCenterY = height / 2f;
/*
* Calculate lengths of different hands based on watch screen size.
*/
mSecondHandLength = (float) (mCenterX * 0.875);
sMinuteHandLength = (float) (mCenterX * 0.75);
sHourHandLength = (float) (mCenterX * 0.5);
/* Scale loaded background image (more efficient) if surface dimensions change. */
float scale = ((float) width) / (float) mBackgroundBitmap.getWidth();
mBackgroundBitmap = Bitmap.createScaledBitmap(mBackgroundBitmap,
(int) (mBackgroundBitmap.getWidth() * scale),
(int) (mBackgroundBitmap.getHeight() * scale), false);
float scale2 = ((float) width) / (float) mSecondBitmap.getWidth();
mSecondBitmap = Bitmap.createScaledBitmap(mSecondBitmap,
12,
222, false);
float scale3 = ((float) width) / (float) mHourBitmap.getWidth();
mHourBitmap = Bitmap.createScaledBitmap(mHourBitmap,
12,139,false);
float scale4 = ((float) width) / (float) mMinuteBitmap.getWidth();
mMinuteBitmap = Bitmap.createScaledBitmap(mMinuteBitmap,
12,
162, false);
private void drawWatchFace(Canvas canvas) {
/*
* Draw ticks. Usually you will want to bake this directly into the photo, but in
* cases where you want to allow users to select their own photos, this dynamically
* creates them on top of the photo.
*/
float innerTickRadius = mCenterX - 10;
float outerTickRadius = mCenterX;
for (int tickIndex = 0; tickIndex < 12; tickIndex++) {
float tickRot = (float) (tickIndex * Math.PI * 2 / 12);
float innerX = (float) Math.sin(tickRot) * innerTickRadius;
float innerY = (float) -Math.cos(tickRot) * innerTickRadius;
float outerX = (float) Math.sin(tickRot) * outerTickRadius;
float outerY = (float) -Math.cos(tickRot) * outerTickRadius;
canvas.drawLine(mCenterX + innerX, mCenterY + innerY,
mCenterX + outerX, mCenterY + outerY, mTickAndCirclePaint);
}
/*
* These calculations reflect the rotation in degrees per unit of time, e.g.,
* 360 / 60 = 6 and 360 / 12 = 30.
*/
final float seconds =
(mCalendar.get(Calendar.SECOND) + mCalendar.get(Calendar.MILLISECOND) / 1000f);
final float secondsRotation = seconds * 6f;
final float minutesRotation = mCalendar.get(Calendar.MINUTE) * 6f;
final float hourHandOffset = mCalendar.get(Calendar.MINUTE) / 2f;
final float hoursRotation = (mCalendar.get(Calendar.HOUR) * 30) + hourHandOffset;
/*
* Save the canvas state before we can begin to rotate it.
*/
canvas.save();
canvas.rotate(hoursRotation, mCenterX, mCenterY);
Matrix matrixHour = new Matrix();
matrixHour.setRotate(0, mCenterX, mCenterY);
canvas.translate(175, 68);
canvas.drawBitmap(mHourBitmap, matrixHour, mHourPaint);
canvas.rotate(minutesRotation - hoursRotation, mCenterX, mCenterY);
Matrix matrixMinute = new Matrix();
matrixMinute.setRotate(0, mCenterX, mCenterY);
canvas.translate(175, -60);
canvas.drawBitmap(mMinuteBitmap, matrixMinute, mMinutePaint);
/*
* Ensure the "seconds" hand is drawn only when we are in interactive mode.
* Otherwise, we only update the watch face once a minute.
*/
if (!mAmbient) {
canvas.rotate(secondsRotation - minutesRotation, mCenterX, mCenterY);
Matrix matrix = new Matrix();
matrixHour.setRotate(0, mCenterX, mCenterY);
canvas.translate(-175,35);
canvas.drawBitmap(mSecondBitmap, matrix, mSecondPaint);
}
/* Restore the canvas' original orientation. */
canvas.restore();
}

LibGDX float with camera position causing black lines with Tiled map

I am creating a top-down shooter game, and whenever I move the camera, or zoom, black likes appear like a grid
I am using Tiled to create the map, and I have the camera following my centered box2d body. I have found that making the camera position equal the position of the box2d body with an int cast results in the black lines disappearing like this:
The problem though, is that because I have the game scaled down, the player will move for a second or two and then when the player reaches the next whole number on either axis, the camera snaps to the player, which is not what I want for the game as it's jarring. The player's movement is granular, but, while rounded, the camera's is not. I do not know if this is a problem with my tile sheet or if it's something I can fix by altering some code. I have tried all different kinds of combinations of padding, and values of spacing and margins. So ultimately, how can I have the camera match the player's position smoothly and not cause the black lines? I'd greatly appreciate any help or recommendations. Thank you in advance!
Where I am type casting the player's float position to an int in game class:
public void cameraUpdate(float delta) {
//timeStep = 60 times a second, velocity iterations = 6, position iterations = 2
world.step(1/60f, 6, 2); //tells game how many times per second for Box2d to make its calculations
cam.position.x = (int)playerOne.b2body.getPosition().x;
cam.position.y = (int)playerOne.b2body.getPosition().y;
cam.update();
}
Majority of player class:
public class PlayerOne extends Sprite implements Disposable{
public World world; // world player will live in
public Body b2body; //creates body for player
private BodyDef bdef = new BodyDef();
private float speed = 1f;
private boolean running;
TextureAtlas textureAtlas;
Sprite sprite;
TextureRegion textureRegion;
private Sound runningSound;
public PlayerOne(World world) {
this.world = world;
definePlayer();
textureAtlas = new TextureAtlas(Gdx.files.internal("sprites/TDPlayer.atlas"));
textureRegion = textureAtlas.findRegion("TDPlayer");
sprite =new Sprite(new Texture("sprites/TDPlayer.png"));
sprite.setOrigin((sprite.getWidth() / 2) / DunGun.PPM, (float) ((sprite.getHeight() / 2) / DunGun.PPM - .08));
runningSound = Gdx.audio.newSound(Gdx.files.internal("sound effects/running.mp3"));
}
public void definePlayer() {
//define player body
bdef.position.set(750 / DunGun.PPM, 400 / DunGun.PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
//create body in the world
b2body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
CircleShape shape = new CircleShape();
shape.setRadius(12 / DunGun.PPM);
fdef.shape = shape;
b2body.createFixture(fdef);
}
public void renderSprite(SpriteBatch batch) {
float posX = b2body.getPosition().x;
float posY = b2body.getPosition().y;
float posX2 = (float) (posX - .14);
float posY2 = (float) (posY - .1);
sprite.setSize(32 / DunGun.PPM, 32 / DunGun.PPM);
sprite.setPosition(posX2, posY2);
float mouseX = Level1.mouse_position.x; //grabs cam.unproject x vector value
float mouseY = Level1.mouse_position.y; //grabs cam.unproject y vector value
float angle = MathUtils.atan2(mouseY - getY(), mouseX - getX()) * MathUtils.radDeg; //find the distance between mouse and player
angle = angle - 90; //makes it a full 360 degrees
if (angle < 0) {
angle += 360 ;
}
float angle2 = MathUtils.atan2(mouseY - getY(), mouseX - getX()); //get distance between mouse and player in radians
b2body.setTransform(b2body.getPosition().x, b2body.getPosition().y, angle2); //sets the position of the body to the position of the body and implements rotation
sprite.setRotation(angle); //rotates sprite
sprite.draw(batch); //draws sprite
}
public void handleInput(float delta) {
setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2 + (5 / DunGun.PPM));
this.b2body.setLinearVelocity(0, 0);
if(Gdx.input.isKeyPressed(Input.Keys.W)){
this.b2body.setLinearVelocity(0f, speed);
}if(Gdx.input.isKeyPressed(Input.Keys.S)){
this.b2body.setLinearVelocity(0f, -speed);
}if(Gdx.input.isKeyPressed(Input.Keys.A)){
this.b2body.setLinearVelocity(-speed, 0f);
}if(Gdx.input.isKeyPressed(Input.Keys.D)){
this.b2body.setLinearVelocity(speed, 0f);
}if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.A)){
this.b2body.setLinearVelocity(-speed, speed);
}if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.D)){
this.b2body.setLinearVelocity(speed, speed);
}
if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.A)){
this.b2body.setLinearVelocity(-speed, -speed );
}if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.D)){
this.b2body.setLinearVelocity(speed, -speed);
}
Where I declare the pixels per meter scale:
public class DunGun extends Game{
public SpriteBatch batch;
//Virtual Screen size and Box2D Scale(Pixels Per Meter)
public static final int V_WIDTH = 1500;
public static final int V_HEIGHT = 800;
public static final float PPM = 100; //Pixels Per Meter
Game render and resize methods:
#Override
public void render(float delta) {
cameraUpdate(delta);
playerOne.handleInput(delta);
//clears screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) {
cam.zoom -= .01;
}
if (Gdx.input.isButtonPressed(Input.Buttons.RIGHT)) {
cam.zoom += .01;
}
mapRenderer.render();
b2dr.render(world, cam.combined); //renders the Box2d world
mapRenderer.setView(cam);
//render our game map
//mapRenderer.render(); // renders map
//mapRenderer.render(layerBackround); //renders layer in Tiled that p1 covers
game.batch.setProjectionMatrix(cam.combined); //keeps player sprite from doing weird out of sync movement
mouse_position.set(Gdx.input.getX(), Gdx.input.getY(), 0);
cam.unproject(mouse_position); //gets mouse coordinates within viewport
game.batch.begin(); //starts sprite spriteBatch
playerOne.renderSprite(game.batch);
game.batch.end(); //starts sprite spriteBatch
//mapRenderer.render(layerAfterBackground); //renders layer of Tiled that hides p1
}
#Override
public void resize(int width, int height) {
viewport.update(width, height, true); //updates the viewport camera
}
I solved it by fiddling around with the padding of the tilesets in GDX Texture Packer. I added 5 pixels of padding around the 32x32 tiles. I set the margins to 2, and spacing to 4 in Tiled. I had tried a lot of different combinations of padding/spacing/margins that didn't work which made me think it was a coding problem, but those settings worked, and I didn't have to round the floats.

libgdx - Shaperender BspLine with orthographic camera not working

I'm trying to draw a curve line using BSpline and ShapeRenderer.
With perspective camera I found myself able to do that.
If I try to use OrthographicCamera, instead, nothing gets rendered on the screen.
My goal is to draw a BSPline with ShapeRenderer and a Sprite that follow the same design as the Shape.
Can anyone tell me how to fix this / what I am doing wrong?
thanks a lot
public class MyGdxGame extends GdxTest implements ApplicationListener {
private SpriteBatch spriteBatch;
ParticleEffect effect;
int emitterIndex;
Array<ParticleEmitter> emitters;
int particleCount = 10;
float fpsCounter;
InputProcessor inputProcessor;
int CAMERA_WIDTH = 640; //Gdx.graphics.getWidth(); if use this function an exception is arose
int CAMERA_HEIGHT = 480; //Gdx.graphics.getHeight(); if use this function an exception is arose
BspHbCached hb;
ShapeRenderer renderer;
int nPoints;
private OrthographicCamera camera;
#Override
public void create () {
hb = new BspHbCached(CAMERA_WIDTH/4, CAMERA_WIDTH/4); // caching points for curve to draw
renderer = new ShapeRenderer();
nPoints = hb.getNumSamplePoints();
camera = new OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT);
camera.position.set(CAMERA_WIDTH / 2f, CAMERA_HEIGHT / 2f, 0);
camera.update();
spriteBatch = new SpriteBatch();
effect = new ParticleEffect();
effect.load(Gdx.files.internal("data/test.p"), Gdx.files.internal("data"));
effect.setPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
// Of course, a ParticleEffect is normally just used, without messing around with its emitters.
emitters = new Array(effect.getEmitters());
effect.getEmitters().clear();
effect.getEmitters().add(emitters.get(0));
inputProcessor = new InputProcessor() {
public boolean touchUp (int x, int y, int pointer, int button) {
return false;
}
Here are my other important methods:
public void render () {
float delta = Gdx.graphics.getDeltaTime();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
renderer.setProjectionMatrix(camera.combined);
spriteBatch.setProjectionMatrix(camera.combined);
for(int i = 0; i < nPoints - 1; i++) // all points contained in bspline to draw
{
renderer.begin(ShapeType.Line);
renderer.setColor(Color.RED);
renderer.line(p1,p2);
renderer.end();
}
spriteBatch.begin();
effect.draw(spriteBatch, delta);
spriteBatch.end();
fpsCounter += delta;
if (fpsCounter > 3) {
fpsCounter = 0;
int activeCount = emitters.get(emitterIndex).getActiveCount();
Gdx.app.log("libgdx", activeCount + "/" + particleCount + " particles, FPS: " + Gdx.graphics.getFramesPerSecond());
}
}
}
NB: my starting point was Path Interface Splines

How to use glRotatef()

I am new to LWJGL but am slowly learning. I was wanting to make a square that rotated when you pressed the key. Like d rotates it 90 degrees as you can tell below, but when I use glRotatef(); it gives me an error and I don't know why. There error tells me I need to create a method for it, I know I don't need to though. Anything helps!
public class MainPlayer {
private Draw draw;
private int rotation;
private float WIDTH = (float) (Display.getWidth() * 0.1);
private float HEIGHT = (float) (WIDTH / 2);
private float x = Display.getWidth() / 2 - WIDTH / 2;
private float y = Display.getHeight() / 2 - HEIGHT / 2;
public MainPlayer(){
draw = new Draw(1.0f, 1.0f, 1.0f, WIDTH, HEIGHT);
}
public void update(){
}
public void render(){
glTranslatef(x, y, 0);
glRotatef(rotation,0,0,1);
draw.render();
}
public void getInput(){
if(Keyboard.isKeyDown(Keyboard.KEY_W)){
rotation = 0;
}
if(Keyboard.isKeyDown(Keyboard.KEY_S)){
rotation = 180;
}
if(Keyboard.isKeyDown(Keyboard.KEY_A)){
rotation = 270;
}
if(Keyboard.isKeyDown(Keyboard.KEY_D)){
rotation = 90;
}
}
}
You create an int rotation and I assume your render() loops the whole time, and you only set rotation in getInput().
So I am assuming that you should declare it as int rotation = 0.
glRotatef() is a OpenGL call to rotate objects, just like glTranslatef() moves them. glRotatef() does it in the same way.
glRotatef(AngleOfRotationf, 0, 1, 0) would rotate it horisontally, like in this video i just made: http://www.youtube.com/watch?v=SHsssrj9qr8& uses that line to rotate a ship.
Also in that video i demonstrated moving it with glTranslatef().
To use it you must use GL11.glRotatef(), or import static org.lwjgl.opengl.GL11.*;
That probably means that you haven't statically imported glRotatef
Either use
GL11.glRotatef(rotation, 0, 0, 1);
or import it at the beginning of your program with
import static org.lwjgl.opengl.GL11.glRotatef

Categories

Resources