Alright, so i cant figure out how to make this rpg game im working for android have collision.
I draw the map on the screen in a drawable portion that the character is located in. I move the character by a 64 amount across the screen and when it hits the bounds of the screen it will then move the map and look like the character is moving across the map. It stop when the map hits the end it doesnt move the screen any more. What im trying to do is figure out a away to check if my character is in a certain bitmap and not let it pass through. Here is the code for my player moving, and the map itself. The character and the tiles are bitmaps.
Anything else needed to allow you to help me better comment and i will post more and how it works.
Edit:
sp.yp and sp.xp is the position of the character on screen.
This Draw the map to the screen:
public void draw(Canvas canvas){
//How many tiles are on the screen length times width
for(int x = 0; x <= 31;x++){
for(int y = 0; y <= 17;y++){
switch(Map[Mapx + x][Mapy + y]){
case 0:
canvas.drawBitmap(BLOCK_ROCK, x*32,y*32,null);
break;
case 1:
canvas.drawBitmap(BLOCK_OCEAN, x*32,y*32,null);
break;
case 2:
canvas.drawBitmap(BLOCK_GRASS, x*32,y*32,null);
break;
case 3:
canvas.drawBitmap(BLOCK_ROCK, x*32,y*32,null);
break;
case 4:
canvas.drawBitmap(BLOCK_FLOWER, x*32,y*32,null);
break;
}
}
}
}
This is the movment of the player, these methods are called when person hits the keypad i have drawn to the screen:
public void Down(){
if(sp.yp == 512){
if(w.Mapy == w.mapheight - 17 - 1){
}else{
w.Mapy +=1;
}
}else{
sp.setYd(64);
sp.update();
sp.setYd(0);
}
}
public void Left(){
if(sp.xp == box.xMin + 32){
sp.isRight = false;
if(w.Mapx == 0){
}else{
w.Mapx -=1;
}
}else{
sp.isRight = false;
sp.setXd(-64);
sp.update();
sp.xd = 0;
}
}
public void Jump(){
if(sp.yp == 64){
if(w.Mapy == 0){
}else{
w.Mapy -=1;
}
}else{
sp.setYd(-64);
sp.update();
sp.setYd(0);
}
}
public void Right(){
if(sp.xp == 992){
sp.isRight = true;
if(w.Mapx == w.mapwidth - 31 - 1){
}else{
w.Mapx +=1;
}
}else{
sp.isRight = true;
sp.setXd(64);
sp.update();
sp.xd = 0;
}
}
You should look into a game engine to handle this type of thing. There are several that are easy to import into your project and provide a great deal of functionality so you can work on designing the game and media resources more. Trust me, you probably don't want to code the whole engine.
Check
AndEngine - http://www.andengine.org/
Libgdx - http://code.google.com/p/libgdx/
I suggest AndEngine because there is a great app of simple examples you can use to experiment with. You can find it on:
code.google.com/p/ andengineexamples/
(no space in the address... sorry couldn't post more than two links)
Related
I am writing a Chess program in Java. In my Board class, which deals with all movements of the Piece, I created a function called movePiece that moves a piece to a specific location and captures the enemy block if it exists on that location. The function for the movePiece looks like this:
public void movePiece(int x, int y, Piece pieceToMove) {
if(pieceToMove.canMove(board, this.x, this.y, x, y)){ //Check if the piece canMove to the location
if(board[x][y] == null) { //Check if the location is empty
removePiece(this.x, this.y);
board[x][y] = pieceToMove;
} else {
if(board[x][y].getColor() != pieceToMove.getColor()) { //Check if the location is occupied by an enemy
removePiece(this.x, this.y);
board[x][y] = pieceToMove;
} else {
System.out.println("Invalid Move");
}
}
} else {
System.out.println("Invalid Move");
}
}
It works fine, but I wanted to keep in track of the captured enemy Piece in an ArrayList. So, I created an ArrayList capturedList inside a Player class to keep in track of it, and tried to add
if(board[x][y].getColor() != pieceToMove.getColor()) { //Check if the location is occupied by an enemy
addCapturedPiece(board[x][y], capturedList); <--- THIS LINE
removePiece(this.x, this.y);
board[x][y] = pieceToMove;
}
But this did not work because capturedList is inside the Player class. Is there a way to make this work smoothly?
You could make addCapturedPiece a method in the Player class. Then, the player that is moving the current piece can call that method and add the piece to his/her specific capturedList. For instance:
/***** in Player class *****/
private LinkedList<Piece> capturedList = new LinkedList<Piece>();
// ...
private static void addCapturedPiece(Piece p)
{
capturedList.add(p);
}
/***** in your movePiece method *****/
player1.addCapturedPiece(board[x][y]);
I am reading "Learning Java by Building Android Games" and in a Retro Squash Game example I don't know how to implement collision detection for the racket. The movement of the racket uses onTouchEvent. I have tried to implement an if statement but it deosn't get checked until the next touch event- so it doesn't work properly. Please help.
//Event that handles in which direction is the racket moving according to where is the user touching the screen
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
//gets the movement action without the pointers(ACTION_MASK) ??? -U: handles multitouch
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
//what happens if user touches the screen and holds
case MotionEvent.ACTION_DOWN:
//if the screen was touched on the right side of the display than move the racket right
if (motionEvent.getX() >= (screenWidth / 2) && racketPosition.x <= screenWidth) {
racketIsMovingLeft = false;
racketIsMovingRight = true;
} else if (motionEvent.getX() < (screenWidth / 2) && racketPosition.x >= 0) {
racketIsMovingLeft = true;
racketIsMovingRight = false;
} else {
racketIsMovingLeft = false;
racketIsMovingRight = false;
}
break;
//when the user lets go of the screen the racket immediately stops moving
case MotionEvent.ACTION_UP:
racketIsMovingLeft = false;
racketIsMovingRight = false;
break;
}
return true;
}
Ok. I have found the solution. I wasn't looking at the right piece of code - sorry. I have edited the piece which is responsible for changing the racketPoint.x of the racket. Here it is:
public void updateCount() {
//change the racket position according to the movement
if (racketIsMovingRight && (racketPosition.x+racketWidth/2)<=screenWidth) {
racketPosition.x += racketSpeed;
}
if (racketIsMovingLeft && (racketPosition.x-racketWidth/2)>=0) {
racketPosition.x -= racketSpeed;
}
//rest of the code
I have this class which extends SurfaceView. The code that I have so far makes the player follow my finger, but it also allows the player to "teleport" to wherever the finger goes and I do not want that.
#Override
public boolean onTouchEvent(MotionEvent event) {
pointerX = (int)event.getX();
pointerY = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (!player.getPlaying()) {
player.setPlaying(true);
}
if (!player.playerAlive) {
if ((pointerX >= rescaleX(600) && pointerX <= rescaleX(842)) && (pointerY >= rescaleY(900) && pointerY <= rescaleY(1142))) {
//newGame();
player.setX(600);
player.setY(900);
}
}
if (player.playerAlive) {
// player.move(true);
}
break;
case MotionEvent.ACTION_MOVE:
if (!player.getPlaying()){
player.setPlaying(true);
player.move(true);
} else {
player.move(true);
}
break;
case MotionEvent.ACTION_UP:
//player.move(true);
if (!player.playerAlive) {
if ((pointerX >= rescaleX(600) && pointerX <= rescaleX(842)) && (pointerY >= rescaleY(900) && pointerY <= rescaleY(1142))) {
newGame();
player.setX(600);
player.setY(900);
}
}
break;
}
return true;
//return super.onTouchEvent(event);
}
Here is the move() method in the player class:
public void move(boolean b) {
if(b){
if((GamePanel.pointerX * GamePanel.WIDTH / MainActivity.dispX) - 141 >= 1380 - getWidth()){setX(1380-getWidth());}
if((GamePanel.pointerY * GamePanel.HEIGHT / MainActivity.dispY) - 141 >= 1880 - getHeight()){setY(1880 - getHeight());}
setX((int) ((GamePanel.pointerX * GamePanel.WIDTH / MainActivity.dispX) - 141));
setY((int) ((GamePanel.pointerY * GamePanel.HEIGHT / MainActivity.dispY) - 141));
}
Don't "directly" translate finger inputs into 'logic' for moving things.
You should have your onTouchEvent method reads the X and Y values of where a finger press is, and then passes that to some logic. That logic should then decide if that info should be passed to a new method moveCharacterTo(x,y)
the 'logic' I mention above could be several things, You could use the strategy pattern to decide what 'strategy/policy(algorithm)' should be used to process the screen. Or you could just have a single class with a method to compare touch events and see if they are 'close' to the character or not, and then react accordingly.
I'm making a snake game and I've encountered an error.
I have tried two different loops: thread.sleep and Timer.schedule.
I have gotten the same problem.
It will be working fine, but at random intervals, it will start to skip every other frame for 6-10 frames.
In case I wasn't clear, 1 frame is
#Override public void paintComponent(Graphics G){...}
being called. (I have also tried paint)
This has occurred in some other games I've created, but not all. What can I do to fix it?
Here's a full copy of the code:
https://github.com/jnmcd/Snake/blob/master/Code.java
EDIT: I've done some debugging. It appears that the it's not a problem with the paint. The JPanel doesn't always update. What can I do to fix it?
I found what I needed to do. I had to add a revaidate() after the repaint().
Also In the checkKillCollisions you have to break the loop right after you found the losing condition.
Also if the game ends it keeps on showing the error message[Dialog] for which there i no end.So I have created a flag gameOver to check is game is over or not in Snake Class
static Boolean gameOver = false;//Defined in Snake Class
public void checkKillCollisions() {
boolean lose = false;
for (int i = 1; i < Snake.segments.size(); i++) {
if (Snake.segments.get(i).x == x && Snake.segments.get(i).y == y) {
lose = true;
break;//Have to do this
}
}
if (x >= 60 || x < 0 || y >= 60 || y < 0) {
lose = true;
}
if (lose) {
Snake.window.popUp("You Lose");
}
Snake.gameOver = lose;//Will set the gameOVer flag in Snake class
}
And I've modified the Loop class to stop running right after the gameOver flag is set to true
class Loop extends TimerTask {
#Override
public void run() {
if (!Snake.gameOver) {
Snake.updates();
Snake.window.render();
} else {
System.out.println("Game Over");
cancel();
Snake.window.dispose();
}
}
}
I am to create a game in cmd (not gui) in java, its a larger project, but for now, I'd love to know how would I create a 12x12 grid, spawn a player at 0,0 (left top corner) and move him around using keys?
I have attempted to create an array, but didn't seem to get movement to work. I'm a newbie, so would welcome any suggestions.
package hunters;
import java.io.*;
import java.util.*;
import java.awt.*;
public class Hunters {
private static int score;
private static String player = "P";
private static String move;
private static String emptyfield = "X";
private static String [][]a2 = new String [12][12];
private static int pr,cr;
public static void paint_board(){
for (int r = 0 ; r < a2.length; r++){
for (int c= 0; c <a2[r].length; c++){
a2 [r][c] = emptyfield;
a2[pr][cr] = player;
System.out.print(" "+a2[r][c]);
}
System.out.println("");
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
score = 0;
paint_board();
do{
System.out.println("Input your move");
move = in.nextLine();
if (move.equalsIgnoreCase("w")){
//move up
a2[pr-1][cr]= player;
//repaint
paint_board();
//check for collision
//check for health
}else if(move.equalsIgnoreCase("s")){
//move down
a2[pr+1][cr]= player;
//repaint
paint_board();
//check for collision
//check for health
}else if(move.equalsIgnoreCase("d")){
//move right
a2[pr][cr+1] = player;
//repaint
paint_board();
//check for collision
//check for health
}else if(move.equalsIgnoreCase("a")){
//move left
a2[pr][cr-1]=player;
//repaint
paint_board();
//check for collision
//check for health
}
}while(score !=5);
}
}
this is the way i'd like it to work. I have tried to create a separate Position class but I have failed in the process...`
Create a 2D array, have a way to paint a cell in the 2D array (which might contain different objects as defined by the value of the cell). So you might check the square to paint, and if the value is HUMAN (pre-defined constant) then draw a human at that location on the screen.
void paint_cell(int x, int y) {
if (array[x][y] == HUMAN) {
printf("H");
} else if (array[x][y] == ENEMY) {
printf("E");
} else if (array[x][y] == EMPTY) {
printf(" ");
}
}
void paint_maze() {
for (int j = 0; j < 12; j++) {
printf("|");
for (int i = 0; i < 12; i++) {
paint_cell(i,j);
}
printf("|\n");
}
}
When you receive a key event, go to the cell that contains the human and move it to a new destination depending on the key. Then draw the maze again.
"An Array" is definitely the right idea -- a two-dimensional array is probably what I would use to contain the spaces of the grid. But -- what is going to be in the array? Objects that represent the spaces that the user moves through? That's cool; you will have to figure out how to define those spaces, and figure out how to display each one on the screen.
You probably can't use a KeyListener to check for user keystrokes, since KeyListener is part of AWT/Swing, but you will need a way to get input from the keyboard. Reading from stdin is the easy way to go here. You will need to run a loop that listens for user input at the keyboard, and moves the user's "gamepiece" from square to square depending on which key they hit.