Alright so I have an abstract class. Like the following.
public abstract class GameObject {
// VARIABLES //
protected float x = 0;
protected float y = 0;
}
*I actually have more to it than this but this is all that is needed.
What I am wanting to do is change x and y for all the classes extended off GameObject.
So if I did something like
x += 1;
y += 1;
Then every class that extends GameObject has the variables x and y = 1.
How would I go about doing this?
You can't do that as they currently are. They are instance variables, meaning that each instance of GameObject gets its own copy of the variables. If they are static variables, then all instances would share them.
I recommend to use two new variables in the class that renders the game, e.g. viewX and viewY, which you add to an object's x and y before drawing it. By modifying these two variables you can shift around all objects without modifying much data, e.g. like this:
float viewX = 0, viewY = 0;
void render() {
for (GameObject o : gameObjects)
draw(o.image, o.x + viewX, o.y + viewY);
}
void setCamera(float x, float y) {
viewX = x;
viewY = y;
}
Related
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.
If there is an array such as:
//....
int[] anArray;
anArray = new int[3];
anArray[0] = new otherClassWConst( x, y , z);
anArray[1] = new otherClassWConst( x, y , z);
anArray[2] = new otherClassWConst( x, y , z);
//....
With the values of x and y and z all being of different value to the other x, y, and z's from the other objects in the array. (Does that make sense? Like the value of x in anArray[0] is not the same as the value found in anArray[2]). Note: there is a constructor from another class that requires those parameters, I'm not sure if thats important
How do I, in a different class, get the value of one of the parameters (for example, the value of y) in each of the array values. As in, is there a way I can get all three values of the Ys so I can add them all up together in another class?
For example
//code attaining only the y values of the array
overallValueOfY = Y + Y + Y; // or something of that nature
//life continues over here.
Please tell me if something is unclear, I tried so hard to explain. Thank you for the consideration.
OtherClassConst will need to supply a get method for it:
public class OtherClassConst {
private int x;
private int y;
private int x;
public (int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getY() {
return y;
}
/* Same concept for getX() and getZ() */
}
Then, you class can call it:
int sumY = 0;
for (OtherClassConst c : myArray) {
sumY += c.getY();
}
First off, your array won't work unless your new class extends Int, I just want to make sure you know that.
Now, all you have to do is in that new class create an int varriable
int x;
int y;
int z;
and set them equal to what is put in the constructor. Then create a new method that returns the values
public int getX(){
return this.x;
}
public int getY(){
return this.Y;
}
public int getZ(){
return this.Z;
}
You need to create POJO for your other class with x,y and z instance variables, then using setter method of y you can get the values. Iterate over them to get the sum of values.
If you other OtherClass has a getY method that returns an integer then you can use the following to sum them:
Arrays.stream(anArray).mapToInt(OtherClass::getY).sum();
It is worth getting use to using streams rather than for loops.
I have read that " a variable is shadowed if there is another variable with the same name that is closer in scope". I found this Point class with a constructor as an example:
public class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
x = x;
y = y;
}
}
Then I created an object of the Point class in the CreateObjectDemo class below
and printed the value of the variable x.
public class CreateObjectDemo {
public static void main(String[] args) {
Point originOne = new Point(23, 94);
System.out.println(originOne.x);
}
}
After running the compiler, it prints 0. But why doesn't it print 23? I thought that "x = x" in the constructor would be like "23 = 23". Did I misunderstand the definition of shadowing variables?
I thought that "x = x" in the constructor would be like "23 = 23".
Within the constructor, the meaning of the simple name x is always just the parameter. So the assignment x = x in the constructor takes the value of the x parameter and assigning it to the x parameter as well. The instance variable is never touched. (It's not clear what you mean by 23 = 23;, so I can't tell whether or not that's accurate.) Basically, this is a no-op and some IDEs will give you a warning about it.
To force it to copy to the instance variable, you want:
this.x = x;
(And likewise for y, of course.)
0 is the default value for int type variables, and as the warning says, you're shadowing the variables in the constructor so the object variable is never assigned to.
public Point(int x, int y) {
x = x; //assign value of local x to local x
y = y; //assign value of local y to local y
}
You need to use this keyword to refer to the object variables x and y instead of the local variables:
public Point(int x, int y) {
this.x = x; //assign value of local x to object variable x
this.y = y; //assign value of local y to object variable y
}
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
So a section of my assignment is to make a triangle class to be linked to various buttons...but I'm not sure how to make one in eclipse. The specific instructions say this:
Create a triangle class
Data fields: Point[] coords;
constructors
Implement all abstract methods defined in superclass
Getters and setters for each data field
Override public void paint(Graphics arg0) method
I have everything set up in the other classes..except for the triangle class. I'm confused on how to create a triangle using an array of points...Do I need to use Point x,y or somehow store 3 (x,y) coordinate pairs in that one array variable coords? I imagine to create it you would use drawPolygon...but I'm not certain. Any tips?
Here is an example class for Triangle
public class Triangle {
private Point[] coords;
// Null object constructor
public Triangle() {
this.coords = null;
}
// Constructor with point array
public Triangle(Point[] coords) {
this.coords = coords;
}
// Constructor with multiple points
public Triangle(Point a, Point b, Point c) {
this.coords = new Point[3];
coords[0] = a;
coords[1] = b;
coords[2] = c;
}
// The actual paint method
public void paint(Graphics arg0) {
// Setup local variables to hold the coordinates
int[] x = new int[3];
int[] y = new int[3];
// Loop through our points
for (int i = 0; i < coords.length; i++) {
Point point = coords[i];
// Parse out the coordinates as integers and store to our local variables
x[i] = Double.valueOf(point.getX()).intValue();
y[i] = Double.valueOf(point.getY()).intValue();
}
// Actually commit to our polygon
arg0.drawPolygon(x, y, 3);
}
}
Not sure what exactly this class is supposed to be extending, so nothing is marked as an override or anything, and it is missing setters and accessors, but you should be able to make it work.
Use the g.drawPolygon that takes an array of Points as it's args.
Did something similar, where I drew a polygon of three sides. Might help..
for (int i = 0; i < 3; i++){
polygon1.addPoint(
(int) (40 + 50 * Math.cos(i * 2 * Math.PI / 3)),
(int) (150 + 50 * Math.sin(i * 2 * Math.PI / 3))
);
}
g.drawPolygon(polygon1);