player.getX() returning null - java

I've got a function that grabs the players X co-ords and then returns them, but its returning null for some reason I can't quite figure out. (Hence why I'm here).
The exact error I get is as follows:
java.lang.NullPointerException
at dev.colors.level.Level.getXOffset(Level.java:78)
All i do is call this, this is line 78:
if(player.getX() <= half_width){
This line come from this method:
public int getXOffset(){
int offset_x = 0;
//the first thing we are going to need is the half-width of the screen, to calculate if the player is in the middle of our screen
int half_width = (int) (Game.WINDOW_WIDTH/Game.SCALE/2);
//next up is the maximum offset, this is the most right side of the map, minus half of the screen offcourse
int maxX = (int) (map.getWidth()*32)-half_width;
//now we have 3 cases here
if(player.getX() <= half_width){
//the player is between the most left side of the map, which is zero and half a screen size which is 0+half_screen
offset_x = 0;
}else if(player.getX() > maxX){
//the player is between the maximum point of scrolling and the maximum width of the map
//the reason why we substract half the screen again is because we need to set our offset to the topleft position of our screen
offset_x = maxX-half_width;
}else{
//the player is in between the 2 spots, so we set the offset to the player, minus the half-width of the screen
offset_x = (int) (player.getX()-half_width);
}
return offset_x;
}
The getX method is here:
public abstract class LevelObject {
protected float x;
public LevelObject(float x, float y) {
System.out.println(x);
this.x = x;
this.y = y;
public float getX() {
System.out.println(this.x);
return x;
}
}
We declare LevelObject by creating a Player object:
player = new Player(128, 64);
Which then hands the two variables delcared there through the Player.java class, and then through the Character.java class:
public class Player extends Character {
public Player(float x, float y) throws SlickException {
super(x, y);
}
Character.java:
public abstract class Character extends LevelObject {
public Character(float x, float y) throws SlickException {
super(x, y);
}
}
Everything goes through properly up until we call getX (in the LevelObject class, even when I use the System.out to print "this.x" from LevelObject before we call getX it returns the correct variable, "128.0" as declared by the Player object.
To make things weirder, if i put some printlines inside the getX method, they don't show up in the console. It's as if it doesn't even run the method.
This doesn't make any sense to me, and I'm very very lost.

Apparently, the player variable is null.
The getXOffset() does not initialize a player variable, so I guess it must be a class field or something, which must be initialized in a different method.
Perhaps you need to add the this keyword to player initialization code (make it look like this.player = new Player(128, 64);) ?
Either way, your player variable is not initialized properly and that is the reason for that exception.

Related

What is the best time to set resolution-based lengths?

This question will use Processing 3+ code syntax.
Say I have a class Bullet that spawns at a Player's x position at a set height.
class Bullet
{
int x;
int y = player.y;
int w = SIZE_X / 150;
int h = SIZE_Y / 50;
Bullet()
{
x = player.x;
}
void display()
{
rect(x, y, w, h);
}
}
Say I'm using this Bullet class to spawn a bullet in my Space Invaders game. In SpaceInvaders.pde I'll create a Player class that represents my ship. This Player player has a player.x and player.y component. So, when in SpaceInvaders.pde I call player.shoot() I will create a new Bullet in an ArrayList<Bullet> bulletList.
I'm wondering what the best time is to set certain variables to make sure my computer does as little computation as possible.
Right now I can think of three ways of setting this up:
Like in the code above.
Or:
// In SpaceInvaders.pde:
int BulletYPos = player.y;
int bulletWidth = SIZE_X / somenumber;
int bulletHeight = SIZE_Y / somenumber;
// where SIZE_X / SIZE_Y represent the size of the sketch
// in Class Player:
class Player
{
// <snip ... >
void shoot()
{
new Bullet(x, BulletYPos, bulletWidth, bulletHeight);
}
}
`
// in class Bullet:
class Bullet
{
int x, y, w, h;
Bullet(int _x, int _y, int _w, int _h)
{
x = _x;
y = _y;
w = _w;
h = _h;
}
void display()
{
rect(x, y, w, h);
}
}
That would certainly mean SIZE_X / somenumber would only be calculated once. But, I could also see it being much slower because of the increase in cycles where the computer's assigning values.
Basically my question kind of comes down to:
If I'm saying int y = player.y in class Bullet, does it get calculated ONCE, or every time a new Bullet class is made?
My understanding is that the code in the Bullet class's constructor Bullet() gets run each time that a new Bullet is instantiated. But does that mean it's not determining my int y, w, h each time, and does that just once at program launch? Or is it secretly also being called each time I create a new instance of the Bullet class?
In the code you posted, these lines are only running once:
int bulletWidth = SIZE_X / somenumber;
int bulletHeight = SIZE_Y / somenumber;
These lines will run every time you create a new instance of the Bullet class:
Bullet(int _x, int _y, int _w, int _h)
{
x = _x;
y = _y;
w = _w;
h = _h;
}
These lines will also run every time you create a new instance of the Bullet class:
class Bullet
{
int x;
int y = player.y;
int w = SIZE_X / 150;
int h = SIZE_Y / 50;
The values are not recalculated every time you use them.
Note that you can test this yourself using functions. Try something like this:
int sketchX = getSketchX();
void setup() {
size(100, 100);
for(int i = 0; i < 10; i++) {
Bullet b = new Bullet();
}
}
int getSketchX() {
println("getSketchX");
return 42;
}
class Bullet {
int classX = getClassX();
public Bullet() {
int constructorX = getConstructorX();
}
int getClassX() {
println("getClassX");
return 42;
}
int getConstructorX(){
println("getConstructorX");
return 42;
}
}
Taking a step back, I would say that you're probably worrying too much about performance. If you haven't done any benchmarking, you shouldn't be going out of your way to make sure your computer does as little computation as possible. Doing some basic math for each bullet is not going to cause any problems. (Compare that to how much your computer has to do to draw the screen, and you'll see what I mean.)
There's a famous quote: "Premature optimization is the root of all evil." This means that you shouldn't worry too much about optimizing your code if you haven't even measured your code yet.
If you measure your code and find out that the Bullet constructor is indeed taking too long, then you can go ahead and worry about it. But you'll find that your program spends much more time drawing things than it does dividing two numbers.
To answer your question: the best time to set resolution-based lengths is wherever is the most readable.
The most readable location depends on how the different pieces of your code fit together in your brain. And like many things in coding, it's a tradeoff: putting the initialization at the top of your sketch might make sense if you have a lot of constants that will not change, but putting the initialization inside the Bullet constructor might be more readable if you might change the size of each bullet in the future. There isn't a single "best" place to put your code.

Java - ArrayList Objects not deleted properly

I am working on a 2D platformer game for my, last, HS year project.
The game is basically about a player walking back & forward, collecting points and reaching goals... The player can shoot bullets and when bullets hit a block, it is destroyed. Now, I wanted to add an explosion effect using so called "particle" objects. I have written the manager class for it and it seemed to have worked the first time but after shooting a few times, i noticed that the particles stopped getting deleted, they just continue and travel out of screen. The life-time limit is 500ns.
I have also noticed that if i shoot bullets as soon as the game starts, the effect finishes as it is supposed to. but after waiting for a few more seconds and then shooting bullets, the effect particles do not behave as they should.
Here is what it looks like when i shoot bullets as soon as i start the game (What it's supposed to look like):
and here is what it looks like, after waiting a few seconds before shooting the bullets.
ParticleManager.java
public class ParticleManager {
private ArrayList<Particle> particles;
private ArrayList<Particle> removeParticles;
public ParticleManager() {
particles = new ArrayList<Particle>();
removeParticles = new ArrayList<Particle>();
}
public int getListSize() {
return particles.size();
}
/*
Generate particles
*/
public void genParticle(int x, int y, int amount) {
for(int i = 0; i < amount; i++) {
particles.add(new Particle("explosion" , x,y, i));
}
}
public void update() {
// Iterate trough particle objects
// update them & check for lifeTime
for(Particle p: particles) {
// Updating particle object before
// checking for time lapse
p.update();
// Append outdated particles to removeParticles
// if time limit has passed
if(System.nanoTime() - p.timePassed >= Config.particleLife) {
removeParticles.add(p);
}
}
// finally, delete all "remove-marked" objects
particles.removeAll(removeParticles);
}
public void render(Graphics2D g) {
for(Particle p: particles) {
p.render(g);
}
}
}
Particle.java
class Particle {
private double px, py, x, y;
private int radius, angle;
public long timePassed;
String type;
public Particle(String type, double x, double y, int angle) {
this.x = x;
this.y = y;
this.radius = 0;
this.angle = angle;
this.timePassed = 0;
this.type = type; // explosion, tail
}
public void update() {
px = x + radius * Math.cos(angle);
py = y + radius * Math.sin(angle);
radius += 2;
this.timePassed = System.nanoTime();
}
public void render(Graphics2D g) {
g.setColor(Color.WHITE);
g.fillOval((int)px, (int)py, 5, 5);
}
}
I haven't figured out what I am doing wrong here, I've googled about some stuff and at one point i came across an answer mentioning that some references don't get deleted directly for some reason...
and my question is "How can I make these particles vanish after a certain amount of time has passed? - as shown in the first GIF"
I think the problem is that you are constantly overwriting timePassed.
// Updating particle object before
// checking for time lapse
p.update();
// Append outdated particles to removeParticles
// if time limit has passed
if(System.nanoTime() - p.timePassed >= Config.particleLife) {
removeParticles.add(p);
}
p.update() sets timePassed to now and then the if check checks if time passed is far from now (it will never be since it was just set).
I think you do want to set timePassed in the constructor (maybe it would be better named timeCreated).
Additionally, just a heads up, you never clear removeParticles so that list is going to grow forever until it causes the process to run out of memory.

Rectangle Class and containsPoint Method

I am trying to understand the Rectangle Class and MyCircle class, specifically the containsPoint methods in each one.
Here is the code:
public class MyRectangle extends GridItem {
private int height;
private int width;
public MyRectangle(int xValue, int yValue, int w, int h) {
x = xValue;
y = yValue;
width = w;
height = h;
}
public double getArea() {
return height * width;
}
public boolean containsPoint(int xValue, int yValue)
{
return xValue >= x &&
xValue <= x + width &&
yValue >= y &&
yValue <= y + height;
}
}
The confusion I'm having is, what does the containsPoint method mean?
How was this current code set up in this particular way, since isn't that supposed to return a boolean and not data types of the int?
Same dilemma for the MyCircle class.
public class MyCircle extends GridItem {
private int radius;
public MyCircle(int xValue, int yValue, int r)
{
x = xValue;
y = yValue;
radius = r;
}
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
public boolean containsPoint(int xValue, int yValue) {
double dx = x - xValue;
double dy = y - yValue;
double distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
return distance <= radius;
}
}
What exactly are they meaning by the containsPoint method?
How do you interpret this?
Been stumped for days and this is part of a bigger assignment, but cannot comprehend the containsPoint method so it's affect the development of mySquare class.....
So far I've got this..
public class MySquare extends GridItem
{
private int side;
public MySquare(int xValue, int yValue, int s)
{
x = xValue;
y = yValue;
side = s;
}
#Override
public double getArea()
{
return side*side;
}
#Override
public boolean containsPoint(int xValue, int yValue)
{
return x && y;
}
}
How does one apply the containsPoint method in the Square class?
Thanks!
what does the containsPoint method mean?
The method just checks if the given point (the given x,y coordinates i.e. xValue, yValue) is within the current Square or Rectangle.
How was this current code set up in this particular way, since isn't that supposed to return a boolean and not data types of the int?
The method arguments are int because they indicate the x and y coordinates for the given point.
Been stumped for days and this is part of a bigger assignment, but cannot comprehend the containsPoint method so it's affect the development of mySquare class.....
Your sub-classes such as the Sqaure class is supposed to have a set of attributes such as x, y, width, height which indicates the position and size of the square. Based on this set of attributes, check if any given point (xValue, yValue) is within your current square. The same applies for Rectangle class.
The containsPoint is the method to check if a point is inside a specific rectangle / circle / shapes on 2D plane.
Comparing variables with each other will result in an boolean value.
Each comparison in containsPoint() in MyRectangle yields a boolean value which are then connected via and. This means that it will only return true if every single comparison yields true.
You would need to apply the same principle to MySquare.
Think about how the coordinates of the square compare to the coordinates of a point if the point is inside the square.
Let's consider the containsPoint of Rectangle.
Let's assume you have a rectangle of height 2 and width 3 starting at co-ordinate (1,1). So your rectangle would look like this
(1,3) (4,3)
------------
| |
| |
------------
(1,1) (4,1)
(In the above example) given two points xValue and yValue, containsPoint returns true if
xValue is between 1 and 4 (inclusive) and
yValue is between 1 and 3 (inclusive)
and false otherwise
Thus, containsPoint tells whether a given point lies on/within a shape.
The containsPoint method of a circle also does the same thing (whether a point lies within/on the circle), however the formula is a bit more involved. You can refer to the Euclidean distance for two dimensions to understand it better.
The containsPoint for a Square will be very similar to that of a rectangle except for using width and heigth, you would have only one side.
return xValue >= x &&
xValue <= x + side &&
yValue >= y &&
yValue <= y + side;

Java: How do I create an array that will store an Image name and it's X, Y coordinates

I need to create a sticker project for my computer science class. Basically, we have a palette of stickers that we must place on the canvas. The second iteration of our project requires us to code the program such that it will store the name and X, Y coordinates of our image when the image is placed on the canvas. Here is my code so far:
Sticker class
public class Stickers
{
public static int x, y; //create in x and y
public EZImage name; //image name
public Stickers(EZImage name, int Xmouse, int Ymouse) //create member function called Stickers and hold the image name and its x and y positions
{
x = Xmouse; //*****Variable I am trying to get*****
y = Ymouse; //*****Variable I am trying to get*****
}
}
Main Project
int Xmouse; //x coordinate
int Ymouse; //y coordinate
int whatPic = 0; //what pic was last clicked
int placedPic = 0; //what pick was placed
int slot = -1; //correspond to array slot, starting with 0
Stickers[] placedStickers = new Stickers[20];
placedStickers[slot] = new Stickers("Pacman.png", Xmouse, Ymouse);
if (whatPic == 3)
{
if (EZInteraction.wasMouseLeftButtonReleased())
{
if (laptopBack.isPointInElement(Xmouse, Ymouse))
{
EZ.addImage("heisenberg.png", Xmouse, Ymouse);
placedPic = 3;
slot ++; //increment slot by 1
placedStickers[slot] = new Stickers("Pacman.png", Xmouse, Ymouse);
}
}
}
Problem
So I created a while loop that constantly checks what the X, Y coordinate of the mouse is when I place a sticker (that is why the sticker knows where to be placed when clicked on the canvas). I did not include the code for this. My question is, how do I tell the array I want to store the X, Y coordinate of the mouse when I place a sticker on the canvas. i.e, I click on picture1. Name of picture1 gets stored into array. Array stores the X, Y coordinate of my mouse when I placed/clicked sticker1 onto the canvas.
Any help would be appreciated, I need to get this project done by today.

moving shapes with java

I am trying to create a java method, move() that will change the location of my object (which is an ellipse). my ellipse has an initial x,y position so I'd like to move it along the Jframe by calling the following method from the JComponent.
public class ShapeAnimation extends Shape {
public void move() {
xVel=(int)(Math.random()*11);
yVel=(int)(Math.random()*11);
x=xVel+x;
y=yVel+y;
if(x>this.x)
xVel=xVel*-1;
if(y>this.y)
yVel=yVel*-1;
}
}
you are using x variable in x=xVel+x; but it is not declared in function, so java assumes it is this.x
so your code looks like this:
this.x=xVel+this.x;
this.y=yVel+this.y;
if(this.x>this.x) // always false
xVel=xVel*-1;
if(this.y>this.y) // always false
yVel=yVel*-1;
you need to change it to:
int newX = xVel+this.x;
int newY = yVel+this.y;
if( (newX<0) || (newX>this.maxX) )
xVel=xVel*-1;
else
this.x = newX;
if( (newY<0) || (newY>this.maxY) )
yVel=yVel*-1;
else
this.y = newY;
maxX and maxY should have maximum values which x and y can have
NOTE - this code do not move object during some iterations, for teaching purposes I suggest you to update it for such cases

Categories

Resources