Sprite resize libGDX - java

I have a sprite, which I draw with:
sprite.draw(spriteBatch);
This works....
I have two spites showing the same, but with different resolution...
Let's say x1 = h:100px, x2= h:200px
In the very wrapper class of the sprite I have a method like this:
public static void setSclae(float newScale, Sprite sprite) {
// sprite.scale(newScale - sprite.getScaleX());
sprite.setScale(newScale);
}
(I tried both, both didn't work) Documentation: http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/g2d/Sprite.html#setScale(float)
On creation of the wrapper class I call the function like this:
setScale(setSide/(setWidth ? this.sprite.getBoundingRectangle().width : this.sprite.getBoundingRectangle().height));
setWidth => boolean (Do you want to set the height or the width??)
this. sprite is a sprite. Origin #(0,0)
The problem is: I want to set the height, no matter which sprite comes in, to 50px...
For x1: setScale(50/100) -> 0.5f
For x2: setScale(50/200) -> 0.25f
Why the hell does this piese of code not work??
Thanks for helping out
Yours,
Florian
PS: Here the constructor of the wrapper class:
public Drawable(Sprite sprite, Vector2 position, Anchor anchor, float setSide, boolean setWidth, boolean flipH, boolean flipV) {
this.sprite = new Sprite(sprite);
this.sprite.setOrigin(0, 0);
setPosition(anchor, position.x, position.y);
setScale(setSide / (setWidth ? this.sprite.getBoundingRectangle().width : this.sprite.getBoundingRectangle().height));
this.sprite.flip(flipV, flipH);
}

I will answer it myself. How I solved it? I implemented my own "Sprites" class, using TexTureRegion. You might not need everything. Pastebin: http://pastebin.com/1Y25HFBm
The IGameObject interface folows. [You do not need the IIntersect interface...
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public interface IGameObject {
public static enum Anchor {TopLeft, MiddleLeft, LowLeft, TopMiddle, MiddleMiddle, LowMiddle, TopRight, MiddleRight, LowRight}
public void Update(GameTime.GameTimeArgs gameTimeArgs);
public void Draw(SpriteBatch spriteBatch);
public void setPosition(Anchor a, float x, float y);
public void setScale(float newScale);
public String toString();
}
Hope that helps :D
Yours,
Florian

Related

Setting image instead of java standard ellipse Java Processing

I'm trying to create a solar system using processing but I'm stuck at trying to set an image instead of using the java standard elipse image.
I started this at school and it consisted of an ellipse rotating around another ellipse.
package processing;
import processing.core.PApplet;
import processing.core.PImage;
public class SolarSystem extends PApplet{
PImage background;
Pianets earth;
public void settings() {
size(650,500);
}
public void setup() {
background = loadImage("C:\\background\\bg.jpg");
earth = new Pianets(this, width/2,height/2,40, 200, 0);
}
public void draw() {
background(background);
earth.showEarth();
earth.rotateEarth(0.007f);
}
public static void main(String[] args) {
PApplet.main("processing.SolarSystem");
}
}
Planets class
package processing;
import processing.core.PApplet;
public class Pianets {
PApplet vis;
float x0,y0; //centre
float diam;
float r; //distance from the centre
float alpha; //rotation angle
public Pianeti(PApplet applet, float x, float y, float diam,float r, float alpha){
vis = applet;
this.x0=x;
this.y0=y;
this.diam=diam;
this.r=r;
this.alpha=alpha;
}
void rotateEarth(float deltaAlpha){
alpha +=deltaAlpha;
}
void showEarth(){
//drawing the body of object at the centre
vis.ellipse(x0, y0, diam, diam);
float x = x0 + r*vis.cos(alpha);
float y = y0 + r*vis.sin(alpha);
vis.ellipse(x,y,diam,diam);
}
I created two images on paint that are the earth and the sun but I don't know how to set the image up.
Questions like this are best answered by looking at the Processing reference. There's an Image section that lists a loadImage() function for loading an image file, and an image() function for drawing it. Please read those.
You should also get into the habit of breaking your problem down into smaller pieces. For example, instead of posting your whole project (which has nothing to do with loading images right now), try to create a smaller example program that just shows a single image. Get that working perfectly before moving on. Then if you're confused about something, you can post a MCVE along with a specific technical question.
Shameless self-promotion: I wrote a tutorial on images in Processing available here.

(LIBGDX) Rendering Sprite (character) hides a Wall

I'm making a game with Libgdx and I'm using isometric perspective.
I have a problem when rendering my character because the map is loaded from Tiled Map Editor and character is a Sprite.
If I have a wall on layer 0 of the map, when drawing the wall before the Sprite, if the sprite is behind the wall, we will see the Sprite instead of wall (we should see the wall), if rendering the Sprite first, we will see the wall instead of the Sprite when the sprite is in front of the wall (we should see the Sprite). Any idea about fixing this?
I haven't really worked with tiled maps, but I think it goes something like this.
First, in TileEd, create an object layer that will be used for your character sprite. So the layer should be between background stuff and stuff that should obscure your player. Name it something like "characters".
Then, create a MapObject subclass that can render a sprite. Something like this:
public class SpriteMapObject extends MapObject {
private Sprite sprite;
public SpriteMapObject (Sprite sprite) {
this.sprite = sprite;
}
#Override
public Color getColor () {
return sprite.getColor();
}
#Override
public void setColor(Color color){
sprite.setColor(color);
}
public void render(Batch batch){
Color spriteColor = sprite.getColor();
float originalAlpha = spriteColor.a;
spriteColor.a *= getOpacity();
sprite.draw(batch);
spriteColor.a = originalAlpha;
}
}
Now after you load your map and your sprite, you can put the sprite on that layer you prepared:
map.getLayers().get("characters").add(new SpriteMapObject(playerSprite));
You also need to subclass the map renderer so it will render the sprite for you. Use your subclassed version instead of the original. For instance:
public class SpritesOrthogonalTiledMapRenderer extends OrthogonalTiledMapRenderer {
//Override whichever constructor(s) you need
public SpritesOrthogonalTiledMapRenderer (TiledMap map, Batch batch) {
super(map, batch);
}
#Override
public void renderObject(MapObject object) {
super.renderObject(object);
if(object instanceof SpriteMapObject) {
((SpriteMapObject) object).render(batch);
}
}
}
That's the basics of how it works. But if you want your player to be able to be in front or behind of a wall like you described, then you will need to create multiple extra layers, and move your sprite object to different layers when necessary.
Looks to me like Libgdx could use a feature enhancement to OrthogonalTiledMapRenderer so it can draw objects automatically merged into a TileLayer and inserting them into the draw order based on row.
I found an "answer" somewhere else so I share it with you so if any1 else had the problem:
- get players tile location.
- get each tile in that stack ( aka, get a reference to every tile in that cell across each layer.
- check for visibility exceptions on each of those tiles. Store exceptions as properties defined in Tiled. ( will cover properties shortly )
- handle accordingly, most likely by raising or lowering the players render layer for that frame.

Array of Bodies in Box2D (Java)

I'm pretty new to Box2D and have very little programming experiences at all, so please be patient. Currently I am working on a little Breakout game.Something like a really simple version of this:http://i.computer-bild.de/imgs/4/9/8/6/7/5/1/Google-Breakout-745x419-9c0b3d2ebbdeae82.jpg
It is an exercise for my university. At this point I already created the paddle, the ball and the walls. Now I want to create the bricks. My problem is that I'm not sure how to organize them. I thought about making a class for the bricks with 2 floats in the constructer for the actual position of the one brick. Then I wanted to create Arrays of the brick class.
At this point my code looks like this:
private Body brickBody;
private PolygonShape brickShape;
private BodyDef brickBodyDef;
private Fixture brickFixture;
Physik phy;
public CleverBrick(float a, float b, final Physik p) {
brickBodyDef = new BodyDef();
brickBodyDef.type = BodyType.StaticBody;
brickBodyDef.position.set(new Vector2(a,b));
phy =p;
brickBody = Physik.getWorld().createBody(brickBodyDef);
brickShape = new PolygonShape();
brickShape.setAsBox(30,5);
Fixture brickFixture = brickBody.createFixture(brickShape, 0.0f);
brickFixture.setUserData("The brick");
}
public void destroyBrick() {
brickBody.destroyFixture(brickFixture);
}
public Body getBrickbody() {
return brickBody;
}
public void setBrickbody(Body brickbody) {
this.brickBody = brickbody;
}
public PolygonShape getBrickShape() {
return brickShape;
}
public void setBrickShape(PolygonShape brickShape) {
this.brickShape = brickShape;
}
public BodyDef getBrickBodyDef() {
return brickBodyDef;
}
public void setBrickBodyDef(BodyDef brickBodyDef) {
this.brickBodyDef = brickBodyDef;
}
public Fixture getBrickFixture() {
return brickFixture;
}
public void setBrickFixture(Fixture brickFixture) {
this.brickFixture = brickFixture;
}
}
And I try to create the array with this in the main class with these lines:
for (int i =0; i<9; i++) {
bricks[i] = new CleverBrick(100,100, this);
}
Later I want to import different structures of bricks from xml files, this is just a test case.
I always get a NullPointerException at the line :
brickBody = Physik.getWorld().createBody(brickBodyDef);
and I dont know why. I think the problem is about getting the world from
I hope someone can help me with that.
Couple of questions:
what is the class Physik.java?
why do you use floats for the Brick positions? these don't seem like floating point numbers to me, an int feels natural here
regarding NPE - #Atuos is right - watch what is null. Here it seems that either Physik or getWorld() are null values. Shouldn't you write
physik.getWorld.createBody()
Either way - it would be nice if you could amend your question by clearly stating what is it that you're asking and providing more source code - the whole class CleverBrick and Physik

Java - Slick 2D - Placing text (or any graphics) on a rectangle (or any Shape)

I am making an RTS game using Slick 2D. I have a building class and it contains an int called resources. I want the resources variable to become a string and be rendered onto the center of my building (which is just supposed to be a rectangle).
Here's my building class:
package test;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Rectangle;
public class BaseBuilding extends Rectangle{
private int resources;
private Graphics g;
public BaseBuilding(float x, float y, float width, float height) {
super(x, y, width, height);
resources = 0;
g = new Graphics();
} // end constructor
public void render(){
g.drawString("bro wat", resources, resources);
g.setColor(Color.gray);
g.fill(this);
g.drawString(Integer.toString(resources), this.width/2, this.height/2);
} // end update
public int getResources(){
return resources;
} // end getResources
public void addResources(int mulla){
resources += mulla;
if (resources < 0)
resources = 0;
} // end addResources
public void createBasicUnit(){
// create a BasicUnit object in a randomly, valid position close to this object
// TODO
} // end createBasicUnit
} // end class def
So far all my states are working and i got the rectangle to appear appropriately. My g.drawString(str, float, float) code with correct parameters will work on my GameState class(not shown) in its render function, but it gives me this error in my BaseBuilding class:
java.lang.NullPointerException
at org.newdawn.slick.Graphics.drawString(Graphics.java:1366)
at test.BaseBuilding.render(BaseBuilding.java:19)
at test.GameState.render(GameState.java:34)
at org.newdawn.slick.state.StateBasedGame.render(StateBasedGame.java:199)
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:688)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
at test.StateBaseGame.main(StateBaseGame.java:22)
Sat Apr 18 03:18:55 EDT 2015 ERROR:Game.render() failure - check the game code.
org.newdawn.slick.SlickException: Game.render() failure - check the game code.
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:691)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
at test.StateBaseGame.main(StateBaseGame.java:22)
So i dug around and found out it's this line that's causing me problems:
g.drawString(Integer.toString(resources), this.width/2, this.height/2);
Couldn't find it on the internet; help if you can please thanks.
After taking a look at the Slick source code, your problem comes from the font variable inside the Graphics class which is null.
You are instantiating Graphics with the default constructor which does not provide a default value for the font variable. And the other one, as the doc says, only the container should be instantiate Graphics.
So, you should never instantiate Graphics, instead just retrieve it from the GameContainer (getGraphics) which is everywhere, or you can also get g from the render method of your game class (Game, BasicGame, BasicGameState, StateBasedGame, depending on what you use...).
To keep it simple, just pass your Graphics object through your render method:
public void render(Graphics g){
g.drawString("bro wat", resources, resources);
g.setColor(Color.gray);
g.fill(this);
g.drawString(Integer.toString(resources), this.width/2, this.height/2);
} // end update
And inside your Game:
render(GameContainer container, Graphics g) {
myBaseBuilding.render(g);
}

Using rectangles to simulate straight line motion of an object

I am relatively new to Java and have been trying to simulate the motion of an object (say a car) on a straight path.
I want my object to move in steps in the output, instead of appearing just at the last point of the line.
I have used 2 classes :Veh.java - the vehicle object and SimuFrame.java - to create the simulation environment.
I have referred to some online tutorials for ideas: http://www.newthinktank.com/2012/07/java-video-tutorial-52/ (This simulates the asteroids game. Howeer I want my object to move in a straight line instead of in a random direction)
Please help me understand where I am wrong and what to do next..
Thanks a lot.
Here's my code:
import java.awt.*;
import java.awt.event.*;
public class Veh extends Rectangle{
int uLeftX, uLeftY; //upper LH Position for Rectangle
static int height = 20;
static int width = 20;
int[] pathCoords=new int[1000];
int startPosY; // start position of the objet - anywhere on the left bounday of the frame.
int goalPosY; // end position of the objet - anywhere on the right boundary of the frame.
//Constructor to Create a new Veh
public Veh(int startPosY,int goalPosY){
//Create a new rectangle vehicle from super class constructor
super(0, startPosY, height, width);
this.startPosY=startPosY;
this.goalPosY=goalPosY;
this.pathCoords = Pathmove();
}
//Calculating the 1000 points on the line joining (0,startPosY) and (goalPosY,999)
int[] Pathmove(){
//Slope calculation
float s=(float)(this.goalPosY-this.startPosY)/999;
pathCoords[0]=this.startPosY;
System.out.println("First xy pair is: 0," +this.pathCoords[0]);
for(int m=1; m<1000; m++){
pathCoords[m]= (int)(m*s)-(int)((m-1)*s)+ pathCoords[m-1];
}
return pathCoords;
}
//Function to move the Reactangular object along the line using the Y coordinate values from Pathmove()
void move(){
int[] a = (int[])this.pathCoords.clone();
for (int c=0; c<a.length;c++){
this.setLocation(c,a[c]);
}
}
}
This is the code for creating the simulation environment.
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class SimuFrame extends JFrame{
public static int frameWidth=1000;
public static int frameHeight=1000;
public static void main(String[] args){
new SimuFrame();
}
public SimuFrame(){
this.setSize(frameWidth,frameHeight);
this.setTitle("Path Planning Results");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SimuObject SO=new SimuObject();
this.add(SO);
// Used to execute code after a given delay
// The attribute is corePoolSize - the number of threads to keep in
// the pool, even if they are idle
ScheduledThreadPoolExecutor executor= new ScheduledThreadPoolExecutor(5);
executor.scheduleAtFixedRate(new RepaintTheFrame(this), 0L, 20L, TimeUnit.MILLISECONDS);
this.setVisible(true);
}
}
// Class implements the runnable interface
// By creating this thread I want to continually redraw the screen
// while other code continues to execute
class RepaintTheFrame implements Runnable{
SimuFrame theFrame;
public RepaintTheFrame(SimuFrame theFrame){
}
#Override
public void run() {
theFrame.repaint();
}
}
class SimuObject extends JComponent{
//Holds every Veh created
public ArrayList<Veh> vehs=new ArrayList<Veh>();
public SimuObject(){
int startPosY = (int)(Math.random()*999);
int goalPosY = (int)(Math.random()*999);
vehs.add(new Veh(startPosY,goalPosY));
}
public void paint(Graphics g){
// Allows me to make many settings changes in regards to graphics
Graphics2D graphicSettings = (Graphics2D)g;
// Draw a background that is as big as the Simu board
graphicSettings.setColor(Color.WHITE);
graphicSettings.fillRect(0, 0, getWidth(), getHeight());
// Set rendering rules
graphicSettings.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Set the drawing color to red
graphicSettings.setPaint( Color.RED);
// Cycle through all of the Rock objects
for(Veh veh : vehs){
// Move the vehicle
veh.move();
graphicSettings.draw(veh);
}
}
}
You have a number of problems in your code:
You have a (swallowed) NullPointerException (NPE) in RepaintTheFrame.run(), which causes ScheduledThreadPoolExecutor.scheduleAtFixedRate() to run only once, per scheduleAtFixedRate()'s javadoc.
You are moving your car in JComponent.paint().
In any graphical framework, the repaint will be called automatically by the framework, usually on an OS event, e.g. moving the window, moving the mouse over the window, etc.
Your paint() method should only draw. It should not modify your domain model.
Your move() method always ends up with the vehicle at the end. That's probably not your intent. You probably want your move() method to merely increment the car's position.
Moving from a start value to an end value in steps is called interpolation. You want linear interpolation specifically here. Its one of the easiest to grasp.
This page will be of great assistance to you.
Without getting fancy with interpolation, you could just change your move routine like so:
int index =0;
void move(){
//int[] a = (int[])this.pathCoords.clone();
if(index<this.pathCoords.length)
this.setLocation(c,pathCoords[index]);
index+=1;
}
Not sure why you were cloning the array there. It probably isn't necessary.

Categories