Static count(Android) - java

In the method bounce() the value of count in first increment is not taken forward to second increment..I meant supose count=0..then first time i increment count its value becomes 1 nd second time also the vaue becomes 1..thats may be because both count are stored in different memory location...if i make count static then each time i run the application it retains the value stored in it last time which i don't want..i want the value of count in first increment should be taken forward to second increment...also i can't put count outside if loop inside bounce() method as it will give the wroung output..what should i do?
public class Ball {
private Point p; //Represents the x and y position of the Ball
private int c; //Represents the color of the Ball
private int r; //Represents the Radius of the Ball.
private int dx; //Represents the change in x position of the Ball. (Horizontal Speed)
private int dy; //Represents the change in y position of the Ball. (Vertical Speed)
private Paint paint; //Android Object holding the color for drawing on the canvas
public int count = 0;
public Ball(int x,int y,int col,int radius)
{
p=new Point(x,y);
c=col;
r=radius;
paint=new Paint();
dx=0;
dy=0;
}
public int getCount()
{return count;
}
public int getX() //Returns the x position of the ball as an integer
{return p.x;
}
public int getY() //Returns the y position of the ball as an integer
{
return p.y;
}
public int getRadius() //Returns the Radius of the ball as an integer
{return r;
}
public Paint getPaint() //Returns the Paint of the Ball as a Paint Object
{return paint;
}
public void setColor(int col) //Sets the Color of the Ball
{c=col;
if (paint == null)
paint = new Paint();
paint.setColor(col);
}
public void goTo(int x,int y) //Sets the x and y positions of the Ball
{p.x=x;
p.y=y;
}
public void setDX(int speed) //Sets the Horizontal Speed of the Ball
{dx=speed;
}
public void setDY(int speed) //Sets the Vertical Speed of the Ball
{
dy=speed;
}
public void move() //Changes the x and y position by the dx and dy values
{
p.x=p.x+dx;
p.y=p.y+dy;
}
public void setX(int x)
{
p.x = x;
}
public void setY(int y)
{
p.y = y;
}
public int getDX()
{
return p.x;
}
public int getDY()
{
return p.y;
}
public void bounce(Canvas canvas) //Bounces off the Sides of the Canvas
{
move();
if(p.x>canvas.getWidth()|| p.x<0)
{
count++;
dx=dx * -1;
}
if(p.y>canvas.getWidth()|| p.y<0)
{
count++;
dy=dy * -1;
}
MainActivity.tv.setText(String.valueOf(getCount()));
}
}

Just thought I should add my comments as an answer. You should only create one instance of the Ball class and use it. Each time you create a new instance of Ball, you set count = 0

You should use singleton class to maintain your count increment ,and whenever application starts make it zero . instead of static making Singleton class and maintain count in that class using setter and getter method is beat easy .

Related

Random bouncing ball

I found some answers in internet which explain how to make a ball bouncing, but some of them don't helped me (because bounces are not random), and some are very difficult (my knowledge in physics are limited).
Problem : I have a ball which move and bounce, but not randomly, and I want to make this ball bouncing randomly.
I already have this piece of code :
Public Class Ball{
/** Coordinates */
private int x, y;
/** Speed of the ball*/
private int speedX, speedY;
public Ball(int x, int y, int speedX, int speedY) {
this.x = x ;
this.y = y ;
this.speedX = speedX;
this.speedY = speedY;
}
public void moveAndBounce() {
x += speedX ;
y += speedY ;
// Assuming that touchWallHorizontal() and touchWallHorizontal() work
if (touchHorizontalWall()) {
speedX = -speedX ;
}
if (touchVerticalWall()) {
speedY = -speedY ;
}
}
public static void main (String [] args){
Ball ball = new Ball(); // Initialisation
while (true){
ball.moveAndBounce() ;
}
}
}
It works perfectly, but the ball movement is always the same (a rectangle).
Question : is there a way to have a random bouncing without add attributes to the ball (just with coordinates and speed) ?
And if not, is there not too difficult solution to resolve this problem ?
Thanks in advance !
Problem solved. Here is the new code for moveAndBounce() method (Thanks to johnHopkins) :
public void moveAndBounce() {
x += speedX ;
y += speedY ;
Random random = new Random();
if (touchHorizontalWall()) {
if (speedX > 0) {
// New speed between 10 and 15 (you can choose other)
setSpeedX(-random.nextInt(15) + 10);
} else {
setSpeedX(random.nextInt(15) + 10
}
}
if (touchVerticalWall()) {
if (speedY > 0) {
setSpeedY(-random.nextInt(15) + 10);
} else {
setSpeedY(random.nextInt(15) + 10);
}
}
}

java: Enemy player tracking AI for java game

I am creating a game for the first time in java and I'm currently trying to get my zombies to track and follow the player. below is my code. I have created a controller class, and used a linked list to create multiple zombies. Then in my zombies update method I use simple if statements for the zombie to track the player. The problem is that the zombies track to the players initial starting position, but not to where he is moved.
In the zombie update() method I used a System.println(player.getX()); and it showed that the players position was not being updated in the zombies class, so that is why they only track to its starting position. I cant figure out how to fix this. any help would be appreciated.
ZOMBIE CLASS:
public class Zombie extends Entity{
Animation dwn,up, left, right;
BufferedImage north, south, east, west;
Sprites sprites = new Sprites();
Player player = new Player(100,100);
Rectangle boundsZombie;
String direction = "";
public Zombie(int x, int y){
super(x,y);
sprites.create();
boundsZombie = new Rectangle(0,0, 32, 32);
}
public void update(){
if(player.getX() > x){
x = x + 1;
}
if(player.getX() < x){
x = x - 1;
}
if(player.getY() > y){
y = y + 1;
}
if(player.getY() < y){
y = y - 1;
}
System.out.println(player.getX());
}
public Rectangle getBounds(){
return new Rectangle((int) x, (int) y, 32, 32);
}
public void render(Graphics g){
g.drawImage(sprites.zombieNorth, x, y, null);
//g.setColor(Color.red);
//g.fillRect((int) x + boundsZombie.x, (int) y + boundsZombie.y, boundsZombie.width, boundsZombie.height);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
PLAYER CLASS
public class Player extends Entity{
Animation dwn,up, left, right;
BufferedImage north, south, east, west;
Sprites sprites = new Sprites();
KeyManager keyManager = new KeyManager();
Rectangle boundsPlayer;
//Controller c;
boolean movUp, movDwn, movRight, movLeft;
String direction = "";
public Player(int x, int y){
super(x,y);
sprites.create();
dwn = new Animation(100, sprites.player_down);
up = new Animation(100, sprites.player_up);
left = new Animation(100, sprites.player_left);
right = new Animation(100, sprites.player_right);
north = sprites.playerNorth;
south = sprites.playerSouth;
east = sprites.playerEast;
west = sprites.playerWest;
boundsPlayer = new Rectangle(0,0, 32, 32);
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public Rectangle getBounds(){
return new Rectangle((int) x, (int) y, 32, 32);
}
/**
* player tick method, used to move the player
*/
public void update(){
if(Game.getKeyManager().up){
y -= 3;
direction = "north";
}
if(Game.getKeyManager().down){
y += 3;
direction = "south";
}
if(Game.getKeyManager().left){
x -= 3;
direction = "west";
}
if(Game.getKeyManager().right){
x += 3;
direction = "east";
//System.out.println(x);
}
}
public int getX() {
return (int)x;
}
public int getY() {
return (int)y;
}
public String getDirection(){
return direction;
}
/**
* method used to return players facing direction sprite
* #return
*/
public BufferedImage getPlayerDirection(){
if(direction == "north"){
return north;
}
else if(direction == "south"){
return south;
}
else if(direction == "east"){
return east;
}
else{
return west;
}
}
public void render(Graphics g){
g.drawImage(getCurrentAnimationFrame(), (int) x, (int) y, null);
//g.setColor(Color.red);
//g.fillRect((int) x + boundsPlayer.x, (int) y + boundsPlayer.y, boundsPlayer.width, boundsPlayer.height);
}
/**
* method used to return the bufferedImage of current frame
* #return
*/
public BufferedImage getCurrentAnimationFrame(){
if(Game.getKeyManager().right == true){
return right.getCurrentFrame();
}
else if(Game.getKeyManager().left == true){
return left.getCurrentFrame();
}
else if(Game.getKeyManager().up == true){
return up.getCurrentFrame();
}
else if(Game.getKeyManager().down == true){
return dwn.getCurrentFrame();
}
else {
return getPlayerDirection();
}
}
}
This happens because your enemy class has one player object and your game class has a completely different player object. So your player position will always be the same in the enemy class. Hence, it would be more logical to do enemy AI movement in the game class. Your player or enemy class should just hold your character's position, direction or loading a image whether it is a enemy or a player.
I suggest creating a parent class for both enemy and player class because they both have similar characteristics.

Collision Detection with Java, Slick2D and Tiled Map Editor

I've been stuck on collision detection and how to handle it for a VERY long time. I need help understanding how to use collision detection with Tiled map editor. I have the TMX file parsed and displayed with a player, camera and keyboard movement. I'm not sure how to about doing to collision. My map has 2 layers, one for grass and tiles you can walk on, the other is objectLayer. I've seen people saying I should loop through all the tiles in an object layer and assign rectangles to them. I've got NO idea how to do that and I'm looking for some insight.
My main question is: how do I loop through my layer and get all the tiles and assign rectangles to them.
Game Class:
public class Game extends BasicGameState {
Player player;
Camera cam;
Map map = new Map();
public void init(GameContainer container, StateBasedGame sbg) throws SlickException {
map.init();
cam = new Camera(0, 0);
player = new Player(new Image("res/textures/player.png"), container.getWidth() / 2, container.getHeight() / 2, 32, 32);
}
public void update(GameContainer container, StateBasedGame sbg, int delta) throws SlickException {
cam.tick(player);
player.update(container, delta, map);
}
public void render(GameContainer container, StateBasedGame sbg, Graphics g) throws SlickException {
g.translate(-cam.getX(), -cam.getY());
map.render();
player.render(g);
g.translate(cam.getX(), cam.getY());
}
public int getID() {
return 1;
}
}
Player Class:
public class Player {
float x, y;
int width, height;
double velX = 0.4;
double velY = 0.4;
Image img;
public Player(Image img, float x, float y, int width, int height) {
this.img = img;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public void init() throws SlickException {
}
public void update(GameContainer container, int delta, Map map) {
Input input = container.getInput();
if (input.isKeyDown(Input.KEY_D)) x += velX;
if (input.isKeyDown(Input.KEY_A)) x -= velX;
if (input.isKeyDown(Input.KEY_W)) y -= velY;
if (input.isKeyDown(Input.KEY_S)) y += velY;
}
public void render(Graphics g) {
//g.scale(-2, -2);
g.drawImage(img, x, y);
}
public float getX() {
return x;
}
public float getY() {
return y;
}
}
Map class:
public class Map {
TiledMap map;
public void init() throws SlickException {
map = new TiledMap("res/map/zenith.tmx");
}
public void render() throws SlickException {
map.render(0, 0);
}
}
I'm not too familiar with the methods exactly for getting the tile, but it's definitely in the Javadoc. http://slick.ninjacave.com/javadoc/
For checking collisions against a player, you need to change your movement to check whether the new location of the player is going to have a collision, otherwise you'll get stuck on them.
public void update(GameContainer container, int delta, Map map) {
Input input = container.getInput();
float dx = 0, dy = 0;
// add to dx and dy instead of moving the player straight away.
if (input.isKeyDown(Input.KEY_D)) dx += velX;
if (input.isKeyDown(Input.KEY_A)) dx -= velX;
if (input.isKeyDown(Input.KEY_W)) dy -= velY;
if (input.isKeyDown(Input.KEY_S)) dy += velY;
// here we check the collisions, you can fiddle with this if statement and it'll behave differently.
if(dx != 0 || dy != 0){
if(map.checkCollision(x+dx,y+y){
x+=dx;
y+=dy;
}
}
}
As for checking the collision itself you need a new method in your map class that creates a rectangle for the player and checks against a 2D array inside the map class which holds your collisions. You can populate this array when the map is intialised by looping through your Tiled map through the layer you need and checking if the tile is a collision with getTile(x,y). If the tile has the correct properties for a collision you create a rectangle in that location in your 2D array with something like this:
collisionArray[x][y] = new Rectangle(x,y,TILEWIDTH,TILEHEIGHT);
You can now check for the collision inside
map.checkCollision(x,y)
and with a rectangle created for the player using
Rectangle player = new Rectangle(x,y,PLAYERWIDTH,PLAYERHEIGHT);
Putting it all together you can then check for an intersection with any tiles in the collision array with .intersect(r) as mentioned earlier and map.collision can return true to the player which should stop movement of the player.
I hope that wasn't too convoluted, the javadoc is very helpful and Kevin Glass wrote a thing about checking collisions with just 2D arrays, with varying collision box sizes.
http://www.cokeandcode.com/main/tutorials/tile-maps/
Ok, now im getting a null pointer exception in my checkCollision()
public void assignRectangles() {
int objectLayer = map.getLayerIndex("objectLayer");
for (int x = 0; x < map.getWidth(); x++) {
for (int y = 0; y < map.getHeight(); y++) {
if (map.getTileId(x, y, objectLayer) == 1){
collisionArray[x][y] = new Rectangle(x * 32, y * 32, 32, 32);
}
}
}
}
public boolean checkCollision(float x, float y) {
for (int j = 0; j < collisionArray.length; j++) {
for (int i = 0; i < collisionArray[j].length; i++) {
if (collisionArray[j][i].getX() == x || collisionArray[j][i].getY() == y) {
return false;
}
}
}
return true;
}
Im getting it on the line where it say if (collisionArray[j][i].getX() == x || collisionArray[j][i].getY() == y)
Not sure why im getting it though

Trouble java graphics program

I have this java program that is made up of different classes. But it basically displays a circle and rectangle moving in a frame a Brownian motion.
I am trying to make a triangle class to add an equilateral triangle to the mix and to this I have to modify my nervous shape class and create a equilateral triangle class. I made a triangle class but I am not sure how to modify my nervous shape program to make it work. The nervous shape program work fine on it own without the triage class
I created my triangle class a subclass of shape but I am not sure how to modify nervous shape to make it work. I need to create the triangle class with one instance variable.
Any help will be appreciated.
// Program name: NervousShapes
//
// Displays a frame containing a random mixture of circles
// and rectangles with random colors, sizes, and positions.
// The shapes periodically change position, with the
// direction of motion chosen randomly for each shape. The
// new x coordinate for each shape will either be the same
// as the old x coordinate, one pixel smaller, or one pixel
// larger; the new y coordinate will be computed in a
// similar manner. Shapes will be constrained so that they
// do not move outside the drawing area.
public static void main(String[] args) {
createWindow();
createShapes();
animateShapes();
}
///////////////////////////////////////////////////////////
// NAME: createWindow
// BEHAVIOR: Creates a frame labeled "Nervous Shapes",
// displays the frame, and sets the size of
// the frame (using the WINDOW_SIZE class
// variable). Assigns the frame to the df
// class variable, and assigns the frame's
// graphics context to the g class variable.
// PARAMETERS: None
// RETURNS: Nothing
///////////////////////////////////////////////////////////
private static void createWindow() {
// Create a frame labeled "Nervous Shapes" and set its
// size
df = new DrawableFrame("Nervous Shapes");
df.show();
df.setSize(WINDOW_SIZE, WINDOW_SIZE);
// Get the frame's graphics context
g = df.getGraphicsContext();
}
///////////////////////////////////////////////////////////
// NAME: createShapes
/ / BEHAVIOR: Creates enough Circle and Rectangle objects
// to fill the shapes array. Each shape has a
// random color, size, and position. The height
// and width of each shape must lie between
// MIN_SIZE and MAX_SIZE (inclusive). The
// position is chosen so that the shape is
// completely within the drawing area.
// PARAMETERS: None
// RETURNS: Nothing
///////////////////////////////////////////////////////////
private static void createShapes() {
for (int i = 0; i < shapes.length; i++) {
// Select a random color
int red = generateRandomInt(0, 255);
int green = generateRandomInt(0, 255);
int blue = generateRandomInt(0, 255);
Color color = new Color(red, green, blue);
// Decide whether to create a circle or a rectangle
if (Math.random() < 0.5) {
// Generate a circle with a random size and position
int diameter = generateRandomInt(MIN_SIZE, MAX_SIZE);
int x = generateRandomInt(0, WINDOW_SIZE - diameter);
int y = generateRandomInt(0, WINDOW_SIZE - diameter);
shapes[i] = new Circle(x, y, color, diameter);
} else {
// Generate a rectangle with a random size and
// position
int width = generateRandomInt(MIN_SIZE, MAX_SIZE);
int height = generateRandomInt(MIN_SIZE, MAX_SIZE);
int x = generateRandomInt(0, WINDOW_SIZE - width);
int y = generateRandomInt(0, WINDOW_SIZE - height);
shapes[i] = new Rectangle(x, y, color, width, height);
}
}
}
///////////////////////////////////////////////////////////
// NAME: animateShapes
// BEHAVIOR: Establishes an infinite loop in which the
// shapes are animated. During each loop
// iteration, the drawing area is cleared and
// the shapes are then drawn at new positions.
// The new x and y coordinates for each shape
// will either be the same as the old ones,
// one pixel smaller, or one pixel larger. A
// shape is not moved if doing so would cause
// any portion of the shape to go outside the
// drawing area. At the end of each animation
// cycle, there is a brief pause, which is
// controlled by the delay constant.
// PARAMETERS: None
// RETURNS: Nothing
///////////////////////////////////////////////////////////
private static void animateShapes() {
while (true) {
// Clear drawing area
g.setColor(Color.white);
g.fillRect(0, 0, WINDOW_SIZE - 1, WINDOW_SIZE - 1);
for (int i = 0; i < shapes.length; i++) {
// Change the x coordinate for shape i
int dx = generateRandomInt(-1, +1);
int newX = shapes[i].getX() + dx;
if (newX >= 0 &&
newX + shapes[i].getWidth() < WINDOW_SIZE)
shapes[i].move(dx, 0);
// Change the y coordinate for shape i
int dy = generateRandomInt(-1, +1);
int newY = shapes[i].getY() + dy;
if (newY >= 0 &&
newY + shapes[i].getHeight() < WINDOW_SIZE)
shapes[i].move(0, dy);
// Draw shape i at its new position
shapes[i].draw(g);
}
// Call repaint to update the screen
df.repaint();
// Pause briefly
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {}
}
}
///////////////////////////////////////////////////////////
// NAME: generateRandomInt
// BEHAVIOR: Generates a random integer within a
// specified range.
// PARAMETERS: min - the lower bound of the range
// max - the upper bound of the range
// RETURNS: A random integer that is greater than or
// equal to min and less than or equal to max
///////////////////////////////////////////////////////////
private static int generateRandomInt(int min, int max) {
return (int) ((max - min + 1) * Math.random()) + min;
}
}
Here is my shape superclass that I use to make my triangle.
// Represents a geometric shape that can be displayed in a
// graphics context
import java.awt.*;
public abstract class Shape {
// Instance variables
private int x;
private int y;
private Color color;
// Constructor
protected Shape(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
// Abstract methods
public abstract void draw(Graphics g);
public abstract int getHeight();
public abstract int getWidth();
// Other instance methods
public Color getColor() {
return color;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move(int dx, int dy) {
x += dx;
y += dy;
}
public void setColor(Color color) {
this.color = color;
}
}
Here is the rectangle subclass needed to make program work
// Represents a rectangle that can be displayed in a graphics
/ / context
import java.awt.*;
public class Rectangle extends Shape {
// Instance variables
private int width;
private int height;
// Constructor
public Rectangle(int x, int y, Color color,
int width, int height) {
super(x, y, color);
this.width = width;
this.height = height;
}
// Instance methods
public void draw(Graphics g) {
g.setColor(getColor());
g.fillRect(getX(), getY(), width, height);
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
}
Here is the circle graphic in the nervous shape.
// Represents a circle that can be displayed in a graphics
// context
import java.awt.*;
public class Circle extends Shape {
// Instance variables
private int diameter;
// Constructor
public Circle(int x, int y, Color color, int diameter) {
super(x, y, color);
this.diameter = diameter;
}
// Instance methods
public void draw(Graphics g) {
g.setColor(getColor());
g.fillOval(getX(), getY(), diameter, diameter);
}
public int getHeight() {
return diameter;
}
public int getWidth() {
return diameter;
}
}
And here is the new triangle class I created and I am trying to make nervous shape program run I have to modify create shape part of my nervous shape.
import java.awt.*;
public class Triangle extends Shape {
// Instance variables
private int leng;
// Constructor
public Triangle(int x, int y, Color color,
int leng) {
super(x, y, color);
this.leng=leng;
}
// Instance methods
public void draw(Graphics g) {
int[]Xcoord={getX(),getX()+leng,getX()+leng/2};
int[]Ycoord={getY(),getY(),getY()+math.sqrt(3)/2};
g.drawPolygon(Xcoord,Ycoord,3);
}
public int getleng() {
return leng;
}

Java: Movement, Need to slow it down

Ok so I have been experimenting with java for a few weeks now, following both in class, and online tutorials. I made a simple game where squares fall towards the bottom of the screen, while the player controls a small ball, only moving on the x-axis and trys to avoid them.
The problem that I am having is that the squares start out falling too fast. Right now I have them set as follows:
ix = 0;
iy = 1;
Then in my move() method, I have the following:
hitbox.x += ix;
hitbox.y += iy;
In this example, ix and iy are both integers.
My first assumption was to change the ints to floats, then use:
ix= 0;
iy = 0.5;
and then:
hitbox.x += ix;
hitbox.y += 0.5f;
But this just freezes the objects in their tracks . I believe that this is because cords are taken as integers, so I figured that if I modified my getX() and getY() methods, maybe I could manipulate them somehow to use decimal numbers? But I am not quite sure how to. Any help/hints/solutions to this problem would be Greatly appreciated.
Here is some revelent code, let me know if anymore is needed!
Enemy Manager:
public class EnemyManager {
private int amount;
private List<Enemy> enemies = new ArrayList<Enemy>();
private GameInJavaOne instance;
public EnemyManager(GameInJavaOne instance, int a){
this.amount = a;
this.instance = instance;
spawn();
}
private void spawn(){
Random random = new Random();
int ss = enemies.size();
// If the current amount of enemies is less than the desired amount, we spawn more enemies.
if(ss < amount){
for(int i = 0; i < amount - ss; i++){
enemies.add(new Enemy(instance, random.nextInt(778), random.nextInt(100)+1));
}
// If its greater than the desired number of enemies, remove them.
}else if (ss > 20){
for(int i = 0; i < ss - amount; i++){
enemies.remove(i);
}
}
}
public void draw(Graphics g){
update();
for(Enemy e : enemies) e.draw(g);
}
private void update() {
boolean re = false;
for(int i = 0; i < enemies.size(); i ++){
if(enemies.get(i).isDead()){
enemies.remove(i);
re = true;
}
}
if(re) spawn();
}
public boolean isColliding(Rectangle hitbox){
boolean c =false;
for(int i = 0; i < enemies.size(); i ++){
if(hitbox.intersects(enemies.get(i).getHitbox())) c = true;
}
return c;
}
}
Entity:
public abstract class Entity {
protected int x, y, w, h;
protected boolean removed = false;
public Entity(int x, int y){
this.x = x;
this.y = y;
}
public void Draw(Graphics g){
}
public int getX() { return x; }
public int getY() { return y; }
public int getH() { return h; }
public int getW() { return w; }
}
and the enemy class:
public class Enemy extends Entity{
private Rectangle hitbox;
private int ix, iy;
private boolean dead = false;
private GameInJavaOne instance;
public Enemy(GameInJavaOne instance, int x, int y){
super(x, y);
this.instance = instance;
hitbox = new Rectangle(x, y, 32, 32);
ix = 0;
iy = 1;
}
private void move(){
if(instance.getStage().isCollided(hitbox)){
iy =0;
dead = true;
}
hitbox.x += ix;
hitbox.y += iy;
}
public boolean isDead() {return dead;}
public Rectangle getHitbox() {return hitbox; }
public void draw(Graphics g){
move();
g.setColor(Color.MAGENTA);
g.fillRect(hitbox.x, hitbox.y, hitbox.height, hitbox.width);
}
}
You are using a Rectangle class to represent the position of your box (even though you call it the hitbox), Rectangle does indeed have members x and y which are integers and so when you call
rectangle.x+=0.5f;
What you are really calling is rectangle.x+=(int)0.5f; and (int)0.5f==0.
The Rectangle class is simply inappropriate for holding the position of the box if you want float precision. Consider holding the box's real position as a double or float and casting to int to render it.
So your rendering code would become;
g.fillRect((int)positionX,(int)positionY, hitbox.height, hitbox.width);
where positionX and positionY are doubles. (You could also use Vector2d if you'd prefer to keep x and y together)
Other points
You seem to be extending an Entity class with x,y,w and h and yet never use them, this seems dangerous, why are you extending Entity but recreating your own positional code.
Your game loop isn't shown, however, I can see that you hard code the change in x and y. This is presumably because in your game loop you 'ask for' some frame speed, say 60fps and assume you'll get it. This works fine on a resource rich system, but as soon as you have any resource shortage you will start getting frames that are shorter than 60fps. In most games you don't even notice this because it just makes a larger jump to compensate but here you assume 60fps. It is wise to get an actual frame time and multiply that by a velocity to get you change in x and y.

Categories

Resources