I am currently creating a maze using a pair of boolean array (horizontal and vertical) in order to draw lines for the maze.
The maze only every displays 5 bools from the array at one time. Then, I have an user who is always centered and as he moves through the maze the next set of bools are drawn. This is working as it should.
The issue that I am having is: when the user moves to a certain part of the maze the for loop drawing the lines becomes higher than the bool array and therefore crashes the app. Please find below some code snippets.
The onDraw:
protected void onDraw(Canvas canvas) {
canvas.drawRect(0, 0, width, height, background);
int currentX = maze.getCurrentX(),currentY = maze.getCurrentY();
int drawSizeX = 6 + currentX;
int drawSizeY = 6 + currentY;
currentX = currentX - 2;
currentY = currentY - 2;
for(int i = 0; i < drawSizeX - 1; i++) {
for(int j = 0; j < drawSizeY - 1; j++) {
float x = j * totalCellWidth;
float y = i * totalCellHeight;
if(vLines[i + currentY][j + currentX]) {
canvas.drawLine(x + cellWidth, //start X
y, //start Y
x + cellWidth, //stop X
y + cellHeight, //stop Y
line);
}
if(hLines[i + currentY][j + currentX]) {
canvas.drawLine(x, //startX
y + cellHeight, //startY
x + cellWidth, //stopX
y + cellHeight, //stopY
line);
}
}
//draw the user ball
canvas.drawCircle((2 * totalCellWidth)+(cellWidth/2), //x of center
(2 * totalCellHeight)+(cellWidth/2), //y of center
(cellWidth*0.45f), //radius
ball);
}
EDIT 1 - The Move -
public boolean move(int direction) {
boolean moved = false;
if(direction == UP) {
if(currentY != 0 && !horizontalLines[currentY-1][currentX]) {
currentY--;
moved = true;
}
}
if(direction == DOWN) {
if(currentY != sizeY-1 && !horizontalLines[currentY][currentX]) {
currentY++;
moved = true;
}
}
if(direction == RIGHT) {
if(currentX != sizeX-1 && !verticalLines[currentY][currentX]) {
currentX++;
moved = true;
}
}
if(direction == LEFT) {
if(currentX != 0 && !verticalLines[currentY][currentX-1]) {
currentX--;
moved = true;
}
}
if(moved) {
if(currentX == finalX && currentY == finalY) {
gameComplete = true;
}
}
return moved;
}
If there is anything else that I need to clarify please let me know.
Thanks in advance.
drawSizeX/Y indexes over the array when currentX/Y is high enough (length-6)
So limit the values to Math.min(current + 6, array.length)
Related
I have this match 3 game, but if I swiping outside the game board this error showed to me and crush the app:
java.lang.ArrayIndexOutOfBoundsException: length=9; index=11
I tried to fix this error but I don't know how to make it work when I touch outside the game board, is that way to make touch only inside the game board game or just a way to ignore this error when it's happing?
public void swap()
{
if(swapIndex > 0)
{
switch (direction){
case "right":
board[poseI][poseJ + 1].poseX -= cellWidth/ 8;
board[poseI][poseJ].poseX += cellWidth/ 8;
break;
case "left":
board[poseI][poseJ - 1].poseX += cellWidth/ 8;
board[poseI][poseJ].poseX -= cellWidth/ 8;
break;
case "up":
board[poseI - 1][poseJ].poseY += cellWidth/ 8;
board[poseI][poseJ].poseY -= cellWidth/ 8;
break;
case "down":
board[poseI + 1][poseJ].poseY -= cellWidth/ 8;
board[poseI][poseJ].poseY += cellWidth/ 8;
break;
}
swapIndex--;
}else {
Candies candies;
candies = board[poseI][poseJ];
board[poseI][poseJ] = board[newPoseI][newPoseJ];
board[newPoseI][newPoseJ] = candies;
board[poseI][poseJ].poseX = (int) (poseJ * cellWidth + drawX);
board[poseI][poseJ].poseY = (int) (poseI * cellWidth + drawY);
board[newPoseI][newPoseJ].poseX = (int) (newPoseJ * cellWidth + drawX);
board[newPoseI][newPoseJ].poseY = (int) (newPoseI * cellWidth + drawY);
swapIndex = 8;
if (gameState == GameState.swapping)
{
gameState = GameState.checkSwapping;
// count user moves
increaseUserMove();
}else {
gameState = GameState.nothing;
}
}
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.drawColor(Color.WHITE); // Background Color
// Create Game top Background
canvas.drawBitmap(spriteSheet.topBG , 0, - cellWidth * 2, null);
// Create Game bottom Background
canvas.drawBitmap(spriteSheet.bottomBG , 0, drawY + cellWidth * 9, null);
// Create Game middle Background
canvas.drawBitmap(spriteSheet.bg_middle , 0, drawY, null);
// Create Game Cells
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(Color.BLACK); // cells color
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 9; j++)
{
canvas.drawLine(0, drawY + (i * cellWidth), cellWidth * 10, drawY + (i * cellWidth), p);
canvas.drawLine(j * cellWidth , drawY, j * cellWidth, drawY + cellWidth * 9, p);
}
}
for (Candies[] candie: board)
{
for (Candies candies: candie)
{
candies.drawCandies(canvas, spriteSheet);
}
}
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[0].length; j++)
{
candies.drawCandies(canvas, spriteSheet);
}
}
//canvas.drawBitmap(spriteSheet.candiesBMP, candies.poseX, candies.poseY, null);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
switch (action)
{
case MotionEvent.ACTION_DOWN:
oldX = event.getX();
oldY = event.getY();
poseI = (int) (oldY - drawY) / cellWidth;
poseJ = (int) (oldX - drawX) / cellWidth;
move = true;
break;
case MotionEvent.ACTION_MOVE:
if(gameState == GameState.nothing)
{
float newX = event.getX();
float newY = event.getY();
float deltaX = Math.abs(newX - oldX);
float deltaY = Math.abs(newY - oldY);
if(move && deltaX > 30 || deltaY > 30)
{
// check how many pixels our fingers moved
// if we moved our finger more than 30 pixels we start checking in which direction
move = false;
if (Math.abs(oldX- newX) > Math.abs(oldY - newY))
{
// if the first X touch - the end of the X touch is bigger than the
// first Y touch - the end of the touch Y so the direction is in the X direction
// now we will check which is bigger the oldX or newX for know if its left or right
if(newX > oldX)
{
direction = "right";
newPoseJ = (poseJ + 1);
}else {
direction = "left";
newPoseJ = (poseJ - 1);
}
newPoseI = poseI;
}
if (Math.abs(oldY - newY) > Math.abs(oldX - newX))
{
if(newY > oldY)
{
direction = "down";
newPoseI = (poseI + 1);
}else {
direction = "up";
newPoseI = (poseI - 1);
}
newPoseJ = poseJ;
}
gameState = GameState.swapping;
}
}
break;
}
return true;
}
What would be the easiest and simplest way to keep the fill() the same after clicking (that's when it changes) and then unclicking, and leaving hover?
In this project, I simply made a grid. When the mouse hovers over a specific rect (at x,y) it changes color based on the state it is in. fill(50) is the default, fill(75) is when the mouse is hovering, and fill(100) is when the mouse clicks. But here when the mouse is unclicked it returns to hover fill until the mouse leaves the rectangle. Thanks.
int cols, rows;
int scl = 20;
void setup() {
size(400, 400);
int w = 400;
int h = 400;
cols = w / scl;
rows = h / scl;
}
void draw() {
background(255);
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
int xpos = x*scl;
int ypos = y*scl;
stroke(55);
if((mouseX >= xpos && mouseX <= xpos+scl) &&
(mouseY >= ypos && mouseY <= ypos+scl)){
fill(75);
if (mousePressed == true){
println("Clicked at: " + xpos + " and " + ypos);
fill(100);
//here is the desired location for the fill to remain constant even
//after unclicking and leaving hover
}
println("Mouse at: " + xpos + " and " + ypos);
}else{
fill(50);
}
rect(xpos, ypos, scl, scl);
}
}
}
Stack Overflow isn't really designed for general "how do I do this" type questions. It's for specific "I tried X, expected Y, but got Z instead" type questions. But I'll try to help in a general sense:
You need to store the state of each cell in a data structure, and then use that data structure to draw your scene.
You could do this with a 2D array, where each cell in the array represents a cell in the grid. You could store the state of the cell, or the color directly.
As Kevin said, you should keep the state of your application in a matrix.
boolean[][] matrix = new boolean[21][21];
When you click on a cell, toggle it
if(!matrix[xpos/scl][ypos/scl]) {
matrix[xpos/scl][ypos/scl] = true;
} else {
matrix[xpos/scl][ypos/scl] = false;
}
Inside this loop, check if your current position can be drawn or not
if(matrix[x][y]) {
fill(204, 102, 0); // an orange color
rect(xpos, ypos, scl, scl);
}
So your draw() method should look like this
void draw() {
background(255);
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
int xpos = x*scl;
int ypos = y*scl;
stroke(55);
if((mouseX >= xpos && mouseX <= xpos+scl) &&
(mouseY >= ypos && mouseY <= ypos+scl)){
fill(75);
if (mousePressed == true){
println("Clicked at: " + xpos + " and " + ypos);
if(!matrix[xpos/scl][ypos/scl]) {
matrix[xpos/scl][ypos/scl] = true;
} else {
matrix[xpos/scl][ypos/scl] = false;
}
fill(100);
//here is the desired location for the fill to remain constant even
//after unclicking and leaving hover
}
println("Mouse at: " + xpos + " and " + ypos);
}else{
fill(50);
}
if(matrix[x][y]) {
fill(204, 102, 0);
rect(xpos, ypos, scl, scl);
}
rect(xpos, ypos, scl, scl);
}
}
}
Most learned friends
I have a sprite that moves around on screen but at the moment it just moves diagonally from left to right and goes off screen and then comes back on the other side.
What I would like it to do is bounce off the edges of the screen in a random fashion but, not being all that clued up on maths, I'm struggling to figure out the coordinates to do this.
Below is what I have so far: (this is an updated code for the Sprite class:
public class Sprite {
//x,y position of sprite - initial position (0,50)
// int [] DIRECTION_TO_ANIMATION_MAP = {3, 1, 0, 2};
private static final int BMP_ROWS = 3;
private static final int BMP_COLUMNS = 4;
private int x = 0;
private int y = 0;
private int xSpeed = 5;//Horizontal increment of position (speed)
private int ySpeed;// Vertical increment of position (speed)
private int currentFrame = 0;
private GameView gameView;
private Bitmap spritebmp;
//Width and Height of the Sprite image
private int bmp_width;
private int bmp_height;
// Needed for new random coordinates.
//private Random random = new Random();
public Sprite(GameView gameView) {
this.gameView = gameView;
spritebmp = BitmapFactory.decodeResource(gameView.getResources(),
R.drawable.running_ninja_sprite);
this.bmp_width = spritebmp.getWidth() / BMP_COLUMNS;
this.bmp_height = spritebmp.getHeight() / BMP_ROWS;
/*Random rnd = new Random(System.currentTimeMillis());
xSpeed = rnd.nextInt(45)-5;
ySpeed = rnd.nextInt(25)-5;*/
}
//update the position of the sprite
public void update() {
//if (x < 0 || x > gameView.getWidth() ){ xSpeed = xSpeed * -1;}
//if (y < 0 || y > gameView.getHeight() ){ ySpeed = ySpeed * -1;}
if (x > gameView.getWidth() - bmp_width - xSpeed || x + xSpeed < 0) {
xSpeed = -xSpeed;
}
x = x + xSpeed;
if (y > gameView.getHeight() - bmp_height - ySpeed || y + ySpeed < 0) {
ySpeed = -ySpeed;
}
y = y + xSpeed;
currentFrame = ++currentFrame % BMP_COLUMNS;
//y = random.nextInt(gameView.getWidth());
//wrapAround(); //Adjust motion of sprite.
}
public void draw(Canvas canvas) {
update();
int srcX = currentFrame * bmp_width;
int srcY = 1 * bmp_height; //getAnimationRow()
Rect src = new Rect(srcX, srcY, srcX + bmp_width, srcY + bmp_height);
Rect dst = new Rect(x, y, x + bmp_width, y + bmp_height);
//Draw sprite image
canvas.drawBitmap(spritebmp, x, y, null);
}
/*private int getAnimationRow() {
double dirDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2);
int direction = (int) Math.round(dirDouble) % BMP_ROWS;
return DIRECTION_TO_ANIMATION_MAP[direction];
}*/
public void wrapAround() {
//Code to wrap around
if (x < 0) x = x + gameView.getWidth(); //increment x whilst not off screen
if (x >= gameView.getWidth()) { //if gone of the right sides of screen
x = x - gameView.getWidth(); //Reset x
}
if (y < 0) y = y + gameView.getHeight();//increment y whilst not off screen
if (y >= gameView.getHeight()) {//if gone of the bottom of screen
y -= gameView.getHeight();//Reset y
}
}
// Checks if the sprite was touched
public boolean wasItTouched(float ex, float ey) {
boolean touched = false;
if ((x <= ex) && (ex < x + bmp_width) &&
(y <= ey) && (ey < y + bmp_height)) {
touched = true;
}
return touched;
}
}
It now does bounce off the edge but from top left, diagonally to the right and back up in the same direction and continues to do this back and forth. I'd like it to be random in its direction after hitting the edge. Any suggestions? As you can see from the code I have tried a lot of things but the sprite just keeps on doing this continuous back and forth diagonal motion and I'm at a loss as to what I can do.
Thanks
Just negate your speed every time you hit a wall
if (x < 0 || x > gameView.getWidth() ){ xSpeed = xSpeed * -1;}
if (y < 0 || y > gameView.getHeight() ){ ySpeed = ySpeed * -1;}
/////////////////////////////// Edit
It will fit something like this. You can also remove your wrap function as it is no longer applicable
//update the position of the sprite
public void update() {
x = x + xSpeed;
y = y + xSpeed;
bounce();
}
private void bounce(){
if (x <= 0 || x >= gameView.getWidth() ){ xSpeed = xSpeed * -1;}
if (y <= 0 || y >= gameView.getHeight() ){ ySpeed = ySpeed * -1;}
}
I have been trying to do player intersection with a small project i'm doing, and I can't seem to make it work. I got the Intersection to work with the player and the wall, but it's very buggy, by buggy I mean, it draws the player in the wall then moves him back instantly. (Check Gyazo for gif of this). I'm pretty sure the problem is that it only checks if the player is in the wall, and not WILL be in the wall, but I can't seem to figure out how to check this. This is what I have so far:
public void intersectsBox2(Rectangle r, Rectangle r2) {
P1 = new Point((int) r.getMinX(), (int) r.getMinY());
P2 = new Point((int) r.getMaxX(), (int) r.getMaxY());
P3 = new Point((int) r2.getMinX(), (int) r2.getMinY());
P4 = new Point((int) r2.getMaxX(), (int) r2.getMaxY());
if ((P2.y < P3.y || P1.y > P4.y || P2.x < P3.x || P1.x > P4.x)
&& !intersectsBox(playerRectangle(), noWalls[0])) {
isInsideWalls = true;
}
}
// Gets the players rectangle
public Rectangle playerRectangle() {
return new Rectangle(9 + dx, 23 + dy, 54, 90);
}
This is to make the player Move:
public void playerMovement() {
if (isInsideWalls) {
System.out.println("YOU ARE IN THE BOX!");
if (animation == down) {
dy -= moveSpeed;
isInsideWalls = false;
} else if (animation == up) {
dy += moveSpeed;
isInsideWalls = false;
} else if (animation == left) {
dx += moveSpeed;
isInsideWalls = false;
} else if (animation == right) {
dx -= moveSpeed;
isInsideWalls = false;
}
} else {
// Moves the player
if (moving == downMove) {
dy += moveSpeed;
moving = 0;
} else if (moving == upMove) {
dy -= moveSpeed;
moving = 0;
} else if (moving == leftMove) {
dx -= moveSpeed;
moving = 0;
} else if (moving == rightMove) {
dx += moveSpeed;
moving = 0;
}
}
This is to check for the intersection:
//Checks for intersection
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
intersectsBox2(walls[i][j], playerRectangle());
}
}
Not really sure if this is needed but heres the full Game.java if you need to see this: http://pastebin.com/GrDy689d
Also here is the Gif of the problem: http://i.gyazo.com/1f31f739897af78f81e61cf22ac772db.mp4
P.S: It's on purpose I can only go into 1 box at the moment for testing purposes.
You could move the player, then check to see if it is in a wall and, if it is, undo the move (or better, calculate a new location as the result of a move, check it, and if it is good, only then move the player there). Note that this assumes a single move can't put you all the way on the other side of a wall, but then it looks like your code does, too.
I'm new to java, and game programming and I'm starting my first big project which is a 2D platform puzzle game.
This is my player movement code
if (speedX > 0 && centerX <= 400){
centerX += speedX;
}
if (speedX < 0 && centerX >= 400){
centerX += speedX;
}
if (speedX > 0 && centerX >= 400){
bg1.setSpeedX(-MOVESPEED);
bg2.setSpeedX(-MOVESPEED);
}
if (speedX < 0 && centerX <= 400){
bg1.setSpeedX(MOVESPEED);
bg2.setSpeedX(MOVESPEED);
}
if (speedX == 0){
bg1.setSpeedX(0);
bg2.setSpeedX(0);
}
if(movingRight == true && movingLeft == true ){
bg1.setSpeedX(0);
bg2.setSpeedX(0);
}
// Handles Jumping
if (jumped == true) {
speedY += 1;
}
// Prevents going beyond X coordinate of 0
if (centerX + speedX <= 60) {
centerX = 61;
}
rect.setRect(centerX - 47, centerY - 65, 32, 87);
centerY += speedY;
}
public void moveRight() {
speedX = MOVESPEED;
}
public void moveLeft() {
speedX = -MOVESPEED;
}
public void stopRight() {
movingRight = false;
stop();
}
public void stopLeft() {
movingLeft = false;
stop();
}
private void stop() {
if (movingRight == false && movingLeft == false) {
speedX = 0;
}
if (movingRight == false && movingLeft == true) {
moveLeft();
}
if (movingRight == true && movingLeft == false) {
moveRight();
}
}
public void jump() {
if (jumped == false) {
speedY = JUMPSPEED;
jumped = true;
}
}
and this is the collision code
public void checkCollision(Rectangle rect){
if (rect.intersects(r)){
if(Player.movingRight){
Player.centerX = tileX + 11;
Player.speedX =0;
}
if(Player.movingLeft){
Player.centerX = tileX + 89;
Player.speedX = 0;
}
if(Player.speedY > 0){
Player.centerY = tileY - 25;
Player.speedY = 0;
Player.jumped = false;
}
}
}
There are two problems.The first one is that if I press one of the movement keys when landing the character "teleports" to the right or left.
I know this happens because I programmed it that if the character intersects with the ground while movingRight or movingLeft are true he moves right or left.(I made it this way so the horizonal collision will work) and I cant think of any other way to do it or how to fix it.
The second problem is that if the character moves of a platfrom he does not fall down.
I tryed to fix it by adding to the collision method
else{
speedY += 1;
}
But it made the character disappear for some reason.
Thanks a lot!
This code was originally written in C++ for a 3D platformer. I rewrote it, but there might be some bugs. I can draw a picture later if it's difficult to understand.
public void checkCollision(Rectangle rect){
if(player.intersects(rect)) {
//the rectangles intersect, time to move the player out of the block
if(rect.y+rect.height >= player.y && rect.y+rect.height-0.7f < player.y) { //if the player is at most 0.7 units (you should change this!) below top side
player.y = rect.y+rect.height; //set player to stand on top
speed.y = 0f; //stop the movement
onGround = true;
} else if(rect.y+rect.height > player.y && rect.y < player.y+player.height) { //if the playeer is on the side, but not below
float xEscMinus = (float)Math.abs((rect.x+rect.width)-player.x); //find the distance to the side
float xEscPlus = (float)Math.abs(rect.x-(player.x+player.width));
if(xEscMinus<xEscPlus) {
player.x = rect.x+rect.width;
} else {
player.x = rect.x-player.width;
}
}
}
}