Related
I am trying to create a Pong game and so far I have everything working for me other than the ball. At first I had the ball's x and y axis move up by one space each time. It was working fine until i decided to increase it to 2. I cant figure out what is wrong with my code and I need help.
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Pong extends JPanel implements KeyListener{
int x = 90;
int y = 90;
int rectytop = 30;
int rectytop2 = 30;
int rectybottom = rectytop + 100;
int rectybottom2 = rectytop2 + 100;
int border = 30;
boolean balldown = true;
boolean ballright = true;
boolean playerborderup = false;
boolean playerborderdown = false;
boolean balltouch1 = false;
boolean balltouch2 = false;
private void moveball() {
if (balldown == true){
y = y + 2;
}
if (y == getHeight()-border){
balldown = false;
}
if (balldown == false){
y = y - 2;
}
if (ballright == true){
x = x + 2;
}
if (x == getWidth()-border){
ballright = false;
}
if (ballright == false){
x = x - 2;
}
if (y == 0){
balldown = true;
}
if (x == 0){
ballright = true;
}
if (balltouch1 == false){
if (x == 75){
if(y < rectybottom && y > rectytop){
ballright = true;
}
}
}
if (balltouch2 == false){
if (x == 390 && y < rectybottom2 && y > rectytop2){
ballright = false;
}
}
}
#Override
public void paint(Graphics g){
super.paint(g);
//drawing ball and paddles
g.fillOval(x, y, 30, 30);
g.fillRect(45 , rectytop, 30, 100);
g.fillRect(425, rectytop2, 30, 100);
}
public static void main(String[] args) throws InterruptedException {
//making the window
JFrame f = new JFrame("Pong Game");
Pong game = new Pong();
f.setVisible(true);
f.setSize(500, 500);//1024, 724
f.setResizable(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addKeyListener(game);
//game code
f.add(game);
while (true){
game.repaint();
game.moveball();
Thread.sleep(10);
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
//player one
if (e.getKeyCode() == KeyEvent.VK_W){
if (rectytop == 0){
playerborderup = true;
}
if (rectytop != 0){
playerborderup = false;
}
if (playerborderup == true){
rectytop = rectytop + 0;
rectybottom = rectytop + 100;
repaint();
}
if (playerborderup == false){
rectytop = rectytop - 5;
rectybottom = rectytop + 100;
repaint();
}
}
if (e.getKeyCode() == KeyEvent.VK_S){
if (rectytop == 585){
playerborderdown = true;
}
if (rectytop != 585){
playerborderdown = false;
}
if (playerborderdown == true){
rectytop = rectytop - 0;
rectybottom = rectytop + 100;
repaint();
}
if (playerborderdown == false){
rectytop = rectytop + 5;
rectybottom = rectytop + 100;
repaint();
}
}
//player two
if (e.getKeyCode() == KeyEvent.VK_UP){
if (rectytop2 == 0){
playerborderup = true;
}
if (rectytop2 != 0){
playerborderup = false;
}
if (playerborderup == true){
rectytop2 = rectytop2 + 0;
rectybottom2 = rectytop2 + 100;
repaint();
}
if (playerborderup == false){
rectytop2 = rectytop2 - 5;
rectybottom2 = rectytop2 + 100;
repaint();
}
}
if (e.getKeyCode() == KeyEvent.VK_DOWN){
if (rectytop2 == 585){
playerborderdown = true;
}
if (rectytop2 != 585){
playerborderdown = false;
}
if (playerborderdown == true){
rectytop2 = rectytop2 - 0;
rectybottom2 = rectytop2 + 100;
repaint();
}
if (playerborderdown == false){
rectytop2 = rectytop2 + 5;
rectybottom2 = rectytop2 + 100;
repaint();
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Since you are moving by 2 every time, it may "skip" over some coordinates. Thus when you say
if (y == getHeight()-border){
balldown = false;
}
y might go from getHeight()-border + 1 to getHeight()-border - 1 and never meet this condition. Thus, change it to a range or a less than. Your new code should be
if (y <= getHeight()-border +1){
balldown = false; //change the +1 and -1 to have difference at least speed number
}
Note that you must do the same for the other ifs with ==, change
if (x == getWidth()-border){
ballright = false;
}
if (y == 0){
balldown = true;
}
if (x == 0){
ballright = true;
}
to
if (x <= getWidth()-border +1){
ballright = false;
}
if (y <= 1){
balldown = true;
}
if (x <= 1){
ballright = true;
}
Note that you can resolve the problem also by saying if the position is eer exactly one away from the border, temporarily decrement position by 1 instead of 2.
You are using if (x == 75) to detect collision with the left paddle. But if speed is 2 than the ball's x is always even and never equals 75. For a quick fix, check x against a range: if (x > 60 && x < 75)
I'm a novice programmer, I'm make my first game in Java, and I just implemented a target AI, and now whenever I run it, always lags at start, I would like a explanation on why please or a way to do this better, Thank you in advance.
Code:(for what is most Likely causing the lag)
public class Handler {
//Use Linked Lists
private Animator a;
private boolean renderMini;
private int x, y;
public LinkedList<GameObject> object = new LinkedList<GameObject>();
public LinkedList<EntityObject> entity = new LinkedList<EntityObject>();
public LinkedList<Faction> faction = new LinkedList<Faction>();
public Handler(){
a = new Animator();
this.renderMini = false;
}
public void render(Graphics g){
///if(GameMain.numFrames > 5){
if(renderMini){
a.AnimateMini(g, x, y, 32, 32);
}
for(int i = 0; i < entity.size(); i++){
EntityObject tempObject = entity.get(i);
tempObject.render(g);
}
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.render(g);
}
//}
}
public void tick(){
//if(GameMain.numFrames > 5){
for(int i = 0; i < entity.size(); i++){
EntityObject tempObject = entity.get(i);
tempObject.tick();
}
for(int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.tick();
}
for(int i = 0; i < faction.size(); i++){
Faction tempObject = faction.get(i);
tempObject.tick();
}
//}
}
public void addEntity(EntityObject o){
this.entity.add(o);
}
public void removeEntity(EntityObject o){
this.entity.remove(o);
}
public void addObject(GameObject o){
this.object.add(o);
}
public void removeObject(GameObject o){
if(o instanceof NpcLaser){
x = o.getX();
y = o.getY();
renderMini = true;
}
if(o instanceof PlayerLaser){
x = o.getX();
y = o.getY();
renderMini = true;
}
this.object.remove(o);
}
public void addFaction(Faction f){
this.faction.add(f);
}
public void removeFaction(Faction f){
this.faction.remove(f);
}
}
public class StandardShip extends EntityObject{
private Handler h;
private Random r;
private Animator a;
private Faction ef;
private EntityObject object;
private int desX, desY;
private int lx, ly, targetX, targetY; //target;
private boolean animateReady;
public static int isDead, ran, ra, rn;
public static boolean thisDeath;
public static boolean choAttack, choDefense, choSpeed, choShealth, choCommanding;
public StandardShip(int x, int y, int width, int height, Handler h, Faction f) {
super(x, y, width, height, h);
r = new Random();
a = new Animator();
this.setDeath(false);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.h = h;
/*this.isDead = 0;
this.thisDeath = false;
this.p = p;*/
this.health = 100;
this.animateReady = false;
//this.target = 1;
this.killLim = r.nextInt(4) + 1;
EntityObject.f = f;
EntityObject.f.addMember(this);
this.attackLim = 20;
this.defenseLim = 20;
this.speedLim = 20;
this.shealthLim = 20;
this.commandingLim = 20;
this.currency = 0;
this.attack = r.nextInt(attackLim);
this.defense = r.nextInt(defenseLim) + 1;
this.speed = r.nextInt(speedLim) + 2;
this.shealth = r.nextInt(shealthLim);
this.commanding = r.nextInt(commandingLim);
this.velX = 1;
this.velY = 1;
this.SearchTime = 1000;
this.desX = r.nextInt(Window.screensize.width + 1000);
this.desY = r.nextInt(Window.screensize.height + 1000);
//this.vectW = 5;
rn = r.nextInt(5);
if(rn == 0){
if(attack < 15){
attack = r.nextInt(attackLim) + 15;
}
}
if(rn == 1){
if(defense < 15){
defense = r.nextInt(defenseLim) + 15;
}
}
if(rn == 2){
if(speed < 15){
speed = r.nextInt(speedLim) + 15;
}
}
if(rn == 3){
if(shealth < 15){
shealth = r.nextInt(shealthLim) + 15;
}
}
if(rn == 4){
if(commanding < 15){
commanding = r.nextInt(commandingLim) + 15;
}
}
if(choAttack){
if(attack < 15){
attack = r.nextInt(attackLim) + 15;
}
}
if(choDefense){
if(defense < 15){
defense = r.nextInt(defenseLim) + 15;
}
}
if(choSpeed){
if(speed < 15){
speed = r.nextInt(speedLim) + 15;
}
}
if(choShealth){
if(shealth < 15){
shealth = r.nextInt(shealthLim) + 15;
}
}
if(choCommanding){
if(commanding < 15){
commanding = r.nextInt(commandingLim) + 15;
}
}
}
public void tick() {
x = GameMain.clamp(0, Window.screensize.width + 1000, x);
y = GameMain.clamp(0, Window.screensize.height + 1000, y);
x += velX;
y += velY;
EnemySize = f.isEnemy.size();
if(coolDown > 0){
coolDown--;
coolDown = GameMain.clamp(0, 1000, coolDown);
}
if(this.target == null){
for(int i = 0; i < EnemySize; i++){
ef = EntityObject.f.isEnemy.get(i);
memberSize = ef.members.size();
}
}
for(int i = 0; i < ef.members.size(); i++){
object = ef.members.get(i);
if(object.getX() >= this.x && object.getX() <= this.x + 300){
this.setTarget(object);
System.out.println("TargetSS");
i = ef.members.size();
}
if(object.getY() >= this.y && object.getY() <= this.y + 300){
this.setTarget(object);
System.out.println("TargetSS");
i = ef.members.size();
}
}
if(this.target != null && coolDown <= 0){
targetX = this.target.getX();
targetY = this.target.getY();
attack(targetX, targetY);
coolDown = 500;
}
if(this.target == null){
wander();
}
/*rand = r.nextInt(100);
if(kills == killLim){
level++;
levelUp();
kills = 0;
killLim += killLim/2;
}
x += velX;
y += velY;
if(y < vectY && velY == -1){velY *= -1;}
if(y > vectY && velY == 1){velY *= -1;}
if(x < vectX && velX == -1){velX *= -1;}
if(x > vectX && velX == 1){velX *= -1;}
if(x == vectX){
if(r.nextInt(2) == 0){
vectX = r.nextInt(Window.screensize.width);
}else{
velX = 0;
}
}
if(y == vectY){
if(r.nextInt(2) == 0){
vectY = r.nextInt(Window.screensize.height);
}else{
velY = 0;
}
}*/
if(this.isDamage > 0 && this.isDamage > defense){
health -= isDamage - (defense / 2);
isDamage = 0;
//System.out.println("HELLO");
}
}
public void wander(){
if(y < desY && velY == -1){velY *= -1;}
if(y > desY && velY == 1){velY *= -1;}
if(x < desX && velX == -1){velX *= -1;}
if(x > desX && velX == 1){velX *= -1;}
System.out.println("desY: "+desY+" desX: "
+desX+" Y: "+y+" X: "+x+" velX: "+velX+" velY: "+velY);
if(x == desX){
//if(r.nextInt(2) == 0){
desX = r.nextInt(Window.screensize.width + 1000);
//}else{
velX = 0;
//}
}
if(y == desY){
//if(r.nextInt(2) == 0){
desY = r.nextInt(Window.screensize.height + 1000);
//}else{
velY = 0;
//}
}
}
public void levelUp(){
this.health += r.nextInt(300) + 100;
this.attack += r.nextInt(attackLim);
this.defense += r.nextInt(defenseLim) + 1;
this.speed += r.nextInt(speedLim) + 2;
this.shealth += r.nextInt(shealthLim);
this.commanding += r.nextInt(commandingLim);
if(choAttack){
attack += (r.nextInt(attackLim) + 15)/2;
}
if(choDefense){
defense += (r.nextInt(defenseLim) + 15)/2;
}
if(choSpeed){
speed += (r.nextInt(speedLim) + 15)/2;
}
if(choShealth){
shealth += (r.nextInt(shealthLim) + 15)/2;
}
if(choCommanding){
commanding += (r.nextInt(commandingLim) + 15)/2;
}
}
public void Collision(Graphics g){
/*for(int i = 0; i < h.object.size(); i++){
GameObject tempObject = h.object.get(i);
if(tempObject.getId() == ID.Money){
Money m = (Money) tempObject;
if(getBounds().intersects(tempObject.getBounds())){
currency += m.getCashValue();
h.removeObject(tempObject);
}
}
if(tempObject.getId() == ID.ShipPart){
ShipPart s = (ShipPart) tempObject;
if(getBounds().intersects(tempObject.getBounds())){
numShipParts++;
h.removeObject(tempObject);
}
}
if(tempObject.getId() == ID.Meteor){
Meteor m = (Meteor) tempObject;
if(getBounds().intersects(tempObject.getBounds())){
Rectangle OverLap = getBounds().intersection(tempObject.getBounds());
if(OverLap.height >= OverLap.width){
if(m.isDoesDamage() && !m.isExplodes() && !m.isOnFire()){
this.health -= m.getDamage();
velX *= -2;
}
if(m.isDoesDamage() && m.isExplodes() || m.isDoesDamage() && m.isOnFire()){
if(m.isExplodes()){
a.AnimateExplosion(g, tempObject.getX(), tempObject.getY(), 32, 32);
this.health -= m.getDamage();
if(a.isFin[0]){
h.removeObject(tempObject);
a.isFin[0] = false;
}
}
if(m.isOnFire()){
this.health -= m.getDamage();
velX *= -2;
}
}else{
velX *= -2;
}
}
if(OverLap.width >= OverLap.height){
if(m.isDoesDamage() && !m.isExplodes() && !m.isOnFire()){
this.health -= m.getDamage();
velY *= -2;
}
if(m.isDoesDamage() && m.isExplodes() || m.isDoesDamage() && m.isOnFire()){
if(m.isExplodes()){
this.health -= m.getDamage();
m.setExplodeNow(true);
}
if(m.isOnFire()){
this.health -= m.getDamage();
velY *= -2;
}
}else{
velY *= -2;
}
}
}
}
if(tempObject.getId() == ID.Player){
p = (Player) tempObject;
if(getBounds().intersects(tempObject.getBounds())){
Rectangle OverLap = getBounds().intersection(tempObject.getBounds());
health -= r.nextInt(10) + 10;
p.setDamage(r.nextInt(10) + 10);
if(OverLap.height >= OverLap.width){
tempObject.setVelX(0);
}
if(OverLap.width >= OverLap.height){
tempObject.setVelY(0);
}
}
}
}*/
}
public void attack(int targetX, int targetY){
System.out.println("Hello");
h.addObject(new NpcLaser(x + 60, y + 60, 5, 9, h, f, targetX, targetY, this.attack));
}
public void render(Graphics g) {
a.AnimateEnemy(g, this.x, this.y, this.width, this.height, f);
if(animateReady){
a.AnimateMini(g, lx, ly, ran, ran);
}
if(health <= 0){
setDeath(true);
StandardShip.thisDeath = true;
a.AnimateExplosion(g, x, y, width, height);
if(Animator.isFin[0]){
ra = r.nextInt(10);
isDead++;
if(ra <= 7){
h.addObject(new Money(x, y, 32, 32, ID.Money, h, currency));
}else{
for(int i = 0; i < numShipParts; i++){
h.addObject(new ShipPart(x, y, 32, 32, ID.ShipPart, h));
}
}
h.removeEntity(this);
Animator.isFin[0] = false;
}
}
g.setColor(Color.red);
}
public Rectangle getBounds() {
return new Rectangle(x + 40, y + 37, 50, 50);
}
}
public class NpcLaser extends GameObject{
private Handler h;
private Faction f, ef;
private int laserAim;
private int currentTarget;
private int vectorX, vectorY;
private int damage;
public NpcLaser(int x, int y, int width, int height, Handler h, Faction f, int targetX, int targetY, int attack) {
super(x, y, width, height, h);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.h = h;
this.f = f;
this.vectorX = targetX;
this.vectorY = targetY;
this.damage = attack;
new Animator();
aimAI();
}
public void tick() {
System.out.println("Hello");
//Collision(g);
x += velX;
y += velY;
if(velX == 0 && velY == 0){
h.object.remove();
}
for(int i = 0; i < f.isEnemy.size(); i++){
ef = f.isEnemy.get(i);
}
for(int u = 0; u < ef.members.size(); u++){
EntityObject eo = ef.members.get(u);
if(getBounds().intersects(eo.getBounds())){
eo.setDamage(damage);
h.removeObject(this);
}
}
if(x > Window.screensize.getWidth() + 1200 || x < 0 - 1200){
h.removeObject(this);
}
if(y > Window.screensize.getHeight() + 1200 || y < 0 - 1200){
h.removeObject(this);
}
}
public void aimAI(){
if(x < vectorX){velX = 10;}
if(x > vectorX){velX = -10;}
if(y < vectorY){velY = 10;}
if(y > vectorY){velY = -10;}
if(x <= vectorX + 60 && x >= vectorX - 60){velX = 0;}
if(y <= vectorY + 60 && y >= vectorY - 60){velY = 0;}
}
public void render(Graphics g) {
/*if(p.isRemoveShot()){
h.removeObject(this);
p.setRemoveShot(false);
}*/
if(velX == 10 && velY == 10 || velX == -10 && velY == -10){
laserAim = 3;
}
if(velX == 10 && velY == -10 || velX == -10 && velY == 10){
laserAim = 2;
}
if(velX == 10 && velY == 0 || velX == -10 && velY == 0){
laserAim = 1;
}
if(velX == 0 && velY == 10 || velX == 0 && velY == -10){
laserAim = 0;
}
if(laserAim == 0){
g.drawImage(Assets.playerLaser, x, y, width, height, null);
}
if(laserAim == 1){
g.drawImage(Assets.playerLaser1, x, y, width, height, null);
}
if(laserAim == 2){
g.drawImage(Assets.playerLaser2, x, y, width, height, null);
}
if(laserAim == 3){
g.drawImage(Assets.playerLaser3, x, y, width, height, null);
}
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public int getCurrentTarget() {
return currentTarget;
}
public void setCurrentTarget(int currentTarget) {
this.currentTarget = currentTarget;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
}
Full Source Code Here
for(int i = 0; i < entity.size(); i++){
EntityObject tempObject = entity.get(i);
tempObject.render(g);
}
Your code includes several loops that look like this, and each take quadratic time, because they're running over LinkedList, which requires O(n) time for get. You should almost certainly be using an ArrayList, or at minimum, using a for-each loop, e.g.
for (EntityObject tempObject : entity) {
tempObject.render(g);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
right now I am developing a chess game in java and have been writing the whole game in one java file without doing subclasses and I was hoping I could get some help with that
I want to separate the moves of all the pieces into a new file
can someone show me how to do that
This is the whole file below it is called ChessFrame,
I need help putting all the piece moves in a separate file called ChessMovement.java
I have tryed just taken out the movement but then that breaks everything I could really do with someone showing me
ChessFrame.java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ChessFrame extends JFrame implements MouseListener, MouseMotionListener {
JLayeredPane layeredPane;
JPanel chessBoard;
JLabel chessPiece;
int xAdjustment;
int yAdjustment;
int startX;
int startY;
int initialX;
int initialY;
JPanel panels;
JLabel pieces;
public ChessFrame() {
Dimension boardSize = new Dimension(600, 600);
// Use a Layered Pane for this application
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
layeredPane.addMouseMotionListener(this);
//Add a chess board to the Layered Pane
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout(new GridLayout(8, 8));
chessBoard.setPreferredSize(boardSize);
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < 64; i++) {
JPanel square = new JPanel(new BorderLayout());
chessBoard.add(square);
int row = (i / 8) % 2;
if (row == 0) {
square.setBackground(i % 2 == 0 ? Color.white : Color.gray);
} else {
square.setBackground(i % 2 == 0 ? Color.gray : Color.white);
}
}
// Setting up the Initial Chess board.
for (int i = 8; i < 16; i++) {
pieces = new JLabel(new ImageIcon("WhitePawn.png"));
panels = (JPanel) chessBoard.getComponent(i);
panels.add(pieces);
}
pieces = new JLabel(new ImageIcon("WhiteRook.png"));
panels = (JPanel) chessBoard.getComponent(0);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteKnight.png"));
panels = (JPanel) chessBoard.getComponent(1);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteKnight.png"));
panels = (JPanel) chessBoard.getComponent(6);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteBishup.png"));
panels = (JPanel) chessBoard.getComponent(2);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteBishup.png"));
panels = (JPanel) chessBoard.getComponent(5);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteKing.png"));
panels = (JPanel) chessBoard.getComponent(3);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteQueen.png"));
panels = (JPanel) chessBoard.getComponent(4);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("WhiteRook.png"));
panels = (JPanel) chessBoard.getComponent(7);
panels.add(pieces);
for (int i = 48; i < 56; i++) {
pieces = new JLabel(new ImageIcon("BlackPawn.png"));
panels = (JPanel) chessBoard.getComponent(i);
panels.add(pieces);
}
pieces = new JLabel(new ImageIcon("BlackRook.png"));
panels = (JPanel) chessBoard.getComponent(56);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackKnight.png"));
panels = (JPanel) chessBoard.getComponent(57);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackKnight.png"));
panels = (JPanel) chessBoard.getComponent(62);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackBishup.png"));
panels = (JPanel) chessBoard.getComponent(58);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackBishup.png"));
panels = (JPanel) chessBoard.getComponent(61);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackKing.png"));
panels = (JPanel) chessBoard.getComponent(59);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackQueen.png"));
panels = (JPanel) chessBoard.getComponent(60);
panels.add(pieces);
pieces = new JLabel(new ImageIcon("BlackRook.png"));
panels = (JPanel) chessBoard.getComponent(63);
panels.add(pieces);
}
private Boolean piecePresent(int x, int y) {
Component c = chessBoard.findComponentAt(x, y);
if (c instanceof JPanel) {
return false;
} else {
return true;
}
}
//Check if a piece is a Black piece.
private Boolean checkWhiteOponent(int newX, int newY) {
Boolean oponent;
Component c1 = chessBoard.findComponentAt(newX, newY);
JLabel awaitingPiece = (JLabel) c1;
String tmp1 = awaitingPiece.getIcon().toString();
if (((tmp1.contains("Black")))) {
oponent = true;
} else {
oponent = false;
}
return oponent;
}
//Check if a piece is a White piece.
private Boolean checkBlackOponent(int newX, int newY) {
Boolean oponent;
Component c1 = chessBoard.findComponentAt(newX, newY);
JLabel awaitingPiece = (JLabel) c1;
String tmp1 = awaitingPiece.getIcon().toString();
if (((tmp1.contains("White")))) {
oponent = true;
} else {
oponent = false;
}
return oponent;
}
public void mousePressed(MouseEvent e) {
chessPiece = null;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JPanel) {
return;
}
Point parentLocation = c.getParent().getLocation();
xAdjustment = parentLocation.x - e.getX();
yAdjustment = parentLocation.y - e.getY();
chessPiece = (JLabel) c;
initialX = e.getX();
initialY = e.getY();
startX = (e.getX() / 75);
startY = (e.getY() / 75);
chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
}
public void mouseDragged(MouseEvent me) {
if (chessPiece == null) {
return;
}
chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
}
public void mouseReleased(MouseEvent e) {
if (chessPiece == null) {
return;
}
chessPiece.setVisible(false);
Boolean success = false;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
String tmp = chessPiece.getIcon().toString();
String pieceName = tmp.substring(0, (tmp.length() - 4));
Boolean validMove = false;
//Pawn Moves
//White Pawn
if (pieceName.equals("WhitePawn")) {
if (startY == 1) {
if ((startX == (e.getX() / 75)) && ((((e.getY() / 75) - startY) == 1) || ((e.getY() / 75) - startY) == 2)) {
if ((((e.getY() / 75) - startY) == 2)) {
if ((!piecePresent(e.getX(), (e.getY()))) && (!piecePresent(e.getX(), (e.getY() + 75)))) {
validMove = true;
} else {
validMove = false;
}
} else {
if ((!piecePresent(e.getX(), (e.getY())))) {
validMove = true;
} else {
validMove = false;
}
}
} else {
validMove = false;
}
} else {
int newY = e.getY() / 75;
int newX = e.getX() / 75;
if ((startX - 1 >= 0) || (startX + 1 <= 7)) {
if ((piecePresent(e.getX(), (e.getY()))) && ((((newX == (startX + 1) && (startX + 1 <= 7))) || ((newX == (startX - 1)) && (startX - 1 >= 0))))) {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
if (startY == 6) {
success = true;
}
} else {
validMove = false;
}
} else {
if (!piecePresent(e.getX(), (e.getY()))) {
if ((startX == (e.getX() / 75)) && ((e.getY() / 75) - startY) == 1) {
if (startY == 6) {
success = true;
}
validMove = true;
} else {
validMove = false;
}
} else {
validMove = false;
}
}
} else {
validMove = false;
}
}
}
//Black Pawn
if (pieceName.equals("BlackPawn")) {
if (startY == 6) {
if ((startX == (e.getX() / 75)) && ((((e.getY() / 75) - startY) == -1) || ((e.getY() / 75) - startY) == -2)) {
if ((((e.getY() / 75) - startY) == -2)) {
if ((!piecePresent(e.getX(), (e.getY()))) && (!piecePresent(e.getX(), (e.getY() + 75)))) {
validMove = true;
} else {
validMove = false;
}
} else {
if ((!piecePresent(e.getX(), (e.getY())))) {
validMove = true;
} else {
validMove = false;
}
}
} else {
validMove = false;
}
} else {
int newY = e.getY() / 75;
int newX = e.getX() / 75;
if ((startX - 1 >= 0) || (startX + 1 <= 7)) {
if ((piecePresent(e.getX(), (e.getY()))) && ((((newX == (startX + 1) && (startX + 1 <= 7))) || ((newX == (startX - 1)) && (startX - 1 >= 0))))) {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
if (startY == 1) {
success = true;
}
} else {
validMove = false;
}
} else {
if (!piecePresent(e.getX(), (e.getY()))) {
if ((startX == (e.getX() / 75)) && ((e.getY() / 75) - startY) == -1) {
if (startY == 2) {
success = true;
}
validMove = true;
} else {
validMove = false;
}
} else {
validMove = false;
}
}
} else {
validMove = false;
}
}
}
//End of Pawn Moves
//Knight Moves
//White Knight Code
else if (pieceName.contains("WhiteKnight")) {
// next we need to get the new coordinates for where the piece is being dropped.
int newY = e.getY() / 75;
int newX = e.getX() / 75;
// We need to make sure that the piece is being put back on the board...if its not being on
// the board why would we want to check anything else!
if (((newX < 0) || (newX > 7)) || ((newY < 0) || (newY > 7))) {
validMove = false;
} else {
if (((newX == startX + 1) && (newY == startY + 2)) || ((newX == startX - 1) && (newY == startY + 2)) || ((newX == startX + 2) && (newY == startY + 1)) || ((newX == startX - 2) && (newY == startY + 1)) || ((newX == startX + 1) && (newY == startY - 2)) || ((newX == startX - 1) && (newY == startY - 2)) || ((newX == startX + 2) && (newY == startY - 1)) || ((newX == startX - 2) && (newY == startY - 1))) {
validMove = true;
if (piecePresent(e.getX(), (e.getY()))) {
if (pieceName.contains("White")) {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
} else {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
}
}
} else {
validMove = false;
}
}
} //Black Knight Code
else if (pieceName.contains("BlackKnight")) {
// next we need to get the new coordinates for where the piece is being dropped.
int newY = e.getY() / 75;
int newX = e.getX() / 75;
// We need to make sure that the piece is being put back on the board...if its not being on
// the board why would we want to check anything else!
if (((newX < 0) || (newX > 7)) || ((newY < 0) || (newY > 7))) {
validMove = false;
} else {
if (((newX == startX + 1) && (newY == startY + 2)) || ((newX == startX - 1) && (newY == startY + 2)) || ((newX == startX + 2) && (newY == startY + 1)) || ((newX == startX - 2) && (newY == startY + 1)) || ((newX == startX + 1) && (newY == startY - 2)) || ((newX == startX - 1) && (newY == startY - 2)) || ((newX == startX + 2) && (newY == startY - 1)) || ((newX == startX - 2) && (newY == startY - 1))) {
validMove = true;
if (piecePresent(e.getX(), (e.getY()))) {
if (pieceName.contains("Black")) {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
} else {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
}
}
} else {
validMove = false;
}
}
}
//End of Knight Code
//Bishop Code
//White Bishup
else if (pieceName.contains("WhiteBishup")) {
int newY = e.getY() / 75;
int newX = e.getX() / 75;
boolean inTheWay = false;
int distance = Math.abs(startX - newX);
if (((newX < 0) || (newX > 7)) || ((newY < 0) || (newY > 7))) {
validMove = false;
} else {
validMove = true;
if (Math.abs(startX - newX) == Math.abs(startY - newY)) {
if ((startX - newX < 0) && (startY - newY < 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX + (i * 75)), (initialY + (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX < 0) && (startY - newY > 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX + (i * 75)), (initialY - (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX > 0) && (startY - newY > 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX - (i * 75)), (initialY - (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX > 0) && (startY - newY < 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX - (i * 75)), (initialY + (i * 75)))) {
inTheWay = true;
}
}
}
if (inTheWay) {
validMove = false;
} else {
if (piecePresent(e.getX(), (e.getY()))) {
if (pieceName.contains("White")) {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
} else {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
}
} else {
validMove = true;
}
}
} else { // the move that is being tried is not a diagonal move...
validMove = false;
}
}
} //Black Bishup
else if (pieceName.contains("BlackBishup")) {
int newY = e.getY() / 75;
int newX = e.getX() / 75;
boolean inTheWay = false;
int distance = Math.abs(startX - newX);
if (((newX < 0) || (newX > 7)) || ((newY < 0) || (newY > 7))) {
validMove = false;
} else {
validMove = true;
if (Math.abs(startX - newX) == Math.abs(startY - newY)) {
if ((startX - newX < 0) && (startY - newY < 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX + (i * 75)), (initialY + (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX < 0) && (startY - newY > 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX + (i * 75)), (initialY - (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX > 0) && (startY - newY > 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX - (i * 75)), (initialY - (i * 75)))) {
inTheWay = true;
}
}
} else if ((startX - newX > 0) && (startY - newY < 0)) {
for (int i = 0; i < distance; i++) {
if (piecePresent((initialX - (i * 75)), (initialY + (i * 75)))) {
inTheWay = true;
}
}
}
if (inTheWay) {
validMove = false;
} else {
if (piecePresent(e.getX(), (e.getY()))) {
if (pieceName.contains("Black")) {
if (checkBlackOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
} else {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
} else {
validMove = false;
}
}
} else {
validMove = true;
}
}
} else { // the move that is being tried is not a diagonal move...
validMove = false;
}
}
}
//End of Bishup Code
//Changes to new pawn Piece and Validates Move
if(!validMove){
int location=0;
if(startY ==0){
location = startX;
}
else{
location = (startY*8)+startX;
}
String pieceLocation = pieceName+".png";
pieces = new JLabel( new ImageIcon(pieceLocation) );
panels = (JPanel)chessBoard.getComponent(location);
panels.add(pieces);
}
else{
if(success){
if (c instanceof JLabel){
Container parent = c.getParent();
parent.remove(0);
String promoteTo;
do {
promoteTo = (String) JOptionPane.showInputDialog(null,
"Promote Pawn to :", "Pawn Promotion",
JOptionPane.QUESTION_MESSAGE, null,
new String[]{"Queen", "Bishup", "Knight", "Rook"}, "Queen");
} while (promoteTo == null);
String newPiece = null;
int location = 0;
if (pieceName.contains("White"))
{
location = 56 + (e.getX()/75);
newPiece = "White"+promoteTo;
}
else
{
location = (e.getX()/75);
newPiece = "Black"+promoteTo;
}
pieces = new JLabel( new ImageIcon(newPiece+".png") );
parent = (JPanel)chessBoard.getComponent(location);
parent.add(pieces);
validate();
repaint();
}
}
else{
if (c instanceof JLabel){
Container parent = c.getParent();
parent.remove(0);
parent.add( chessPiece );
}
else {
Container parent = (Container)c;
parent.add( chessPiece );
}
chessPiece.setVisible(true);
}
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
JFrame frame = new ChessFrame();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Any help would be great the code currently has no errors but I dont want to go any further til I have it separated out
thanks for any help
You need to create a Piece class, which has subclasses for all the piece types. Then create a FactoryPieceFactory.getPiece(pieceName, x pos, y pos, chessboard) to get those pieces, and implement a move() method on it which takes your new position, and does all the validation. This leaves your UI logic for rendering the moves here, but pushes the move logic down into the piece objects.
You will probably change this later to create a ChessBoard object, which will allow you to get a piece by it's x,y coordinates, and thus not know the piece's name. chessBoard.getPiece(x,y).move(newX, newY); That will allow you validate moves, plus deal with captures etc, calling back to the board to remove opposing pieces.
You mixed game-logic with GUI elements. You should use the concept of MVC. To refractor your program at this state is a question too unspecific.
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;
}
}
}
}
I have a problem when I upload my sketch to website.
I write a processing program which is a 3D guiding library.This is my code.
//Camera Variables
float x,y,z;
float tx,ty,tz;
float rotX,rotY;
float mX, mY;
float frameCounter;
float xComp, zComp;
float angle;
//Movement Variables
int moveX;
int moveZ;
float vY;
boolean canJump;
boolean moveUP,moveDOWN,moveLEFT,moveRIGHT;
//check input
int m =0;
//Constants
int ground = 0;
int totalBoxes = 100;
int standHeight = 100;
int dragMotionConstant = 10;
int pushMotionConstant = 100;
int movementSpeed = 50; //Bigger number = slower
float sensitivity = 15; //Bigger number = slower
int stillBox = 100; //Center of POV, mouse must be stillBox away from center to move
float camBuffer = 10;
int cameraDistance = 1000; //distance from camera to camera target in lookmode... 8?
//Options
int lookMode = 8;
int spotLightMode = 4;
int cameraMode = 1;
int moveMode = 2;
void setup(){
size(800,600,P3D);
noStroke();
//dwa(#EDEDE8);
//Camera Initialization
//default
x = -28;
y = height/2;
y-= standHeight;
z = -4830;
tx = width/2;
ty = height/2;
tz = 0;
rotX = 0;
rotY = 0;
xComp = tx - x;
zComp = tz - z;
angle = 0;
//Movement Initialization
moveX = 0;
moveX = 0;
moveUP = false;
moveDOWN = false;
moveLEFT = false;
moveRIGHT = false;
canJump = true;
vY = 0;
}
void draw(){
if(z<-5000)
z=-5000;
if(z>9700)
z=9700;
//println(x,y,z ,mouseX , mouseY ,tx ,ty,tz);
//update frame
background(0);
lights();
if(m==1)
{
//rotateY(0.5);
fill(#EAFF0F);
textSize(50);
text("menu", x-100, y, z+300);
// rotateY(0.5);
//the point
pushMatrix();
fill(#FC1919);
translate(-28,300,4000);
box(10, 20000, -10);
popMatrix();
//the point
}
if(spotLightMode == 0)
lights();
else if(spotLightMode == 1)
spotLight(255,255,255,x,y-standHeight,z,tx,ty,tz,PI,1);
else if(spotLightMode == 2)
spotLight(255,255,255,x,y-standHeight-200,z,x+100,y+100,z,frameCounter/10,1);
else if(spotLightMode == 3)
spotLight(255,255,255,width/2,height/2-1000,0,width/2,height/2,0,PI,1);
else if(spotLightMode == 4)
{
pointLight(255,255,255,x,y,z);
}
/*
for(int i=1;i<=7;i++)
{
spotLight(255, 255, 255, -28, 2000, -5500+i*1875, 1, 1, 1, 360, 1);
}*/
//-5500 9500s
//back wall
pushMatrix();
fill(255);
translate(-28,300,-5500);
box(15000, 5000, -100);
popMatrix();
//back wall
//fount wall
pushMatrix();
fill(255);
translate(-28,300,10500);
box(15000, 5000, -100);
popMatrix();
//fount wall
//L1
bookshielf(800,-4000,7,1);
bookshielf(1000,-4000,7,1);
bookshielf(1200,-4000,7,1);
bookshielf(1400,-4000,7,1);
cameraUpdate();
locationUpdate();
jumpManager(10);
//Camera Mode 1 - Original
if(cameraMode == 1)
camera(x,y,z,tx,ty,tz,0,1,0);
//Camera Mode 2 - Matrix'd
/* if(cameraMode == 2){
beginCamera();
camera();
translate(x,y,z);
translate(0,2*-standHeight,0);
rotateX(rotY/100.0); //This seems to work o.o
rotateY(-rotX/100.0);
//rotateX(rotX/100.0);
endCamera();
}*/
//frameCounter++;
}
void cylinder(float w, float h, int sides)
{
float angle;
float[] x = new float[sides+1];
float[] z = new float[sides+1];
translate(0,100,-500);
//get the x and z position on a circle for all the sides
for(int i=0; i < x.length; i++){
angle = TWO_PI / (sides) * i;
x[i] = sin(angle) * w;
z[i] = cos(angle) * w;
}
//draw the top of the cylinder
beginShape(TRIANGLE_FAN);
vertex(0, -h/2, 0);
for(int i=0; i < x.length; i++){
vertex(x[i], -h/2, z[i]);
}
endShape();
//draw the center of the cylinder
beginShape(QUAD_STRIP);
for(int i=0; i < x.length; i++){
vertex(x[i], -h/2, z[i]);
vertex(x[i], h/2, z[i]);
}
endShape();
//draw the bottom of the cylinder
beginShape(TRIANGLE_FAN);
vertex(0, h/2, 0);
for(int i=0; i < x.length; i++){
vertex(x[i], h/2, z[i]);
}
endShape();
}
public void bookshielf(int thex ,int thez ,int theheight ,int therotate)
{
fill(#938056);
if(theheight==7)
{
if(therotate==1)
{
//left
pushMatrix();
translate(thex,0,thez);
box(20, 500, -100);
popMatrix();
//right
pushMatrix();
translate(thex-200,0,thez);
box(20, 500, -100);
popMatrix();
//back
pushMatrix();
translate(thex-100,0,thez+40);
box(220, 500, -30);
popMatrix();
//middle side
for(int i=1;i<7;i++)
{
pushMatrix();
translate(thex-100,-250+71.5*i,thez-10);
box(220, 5, -100);
popMatrix();
}
//top
pushMatrix();
translate(thex-100,250,thez);
box(220, 10, -100);
popMatrix();
//block
pushMatrix();
translate(thex-100,-250,thez);
box(220, 10, -100);
popMatrix();
}
if(therotate==2)
{
//left
pushMatrix();
translate(thex,0,thez);
box(20, 500, -100);
popMatrix();
//right
pushMatrix();
translate(thex-200,0,thez);
box(20, 500, -100);
popMatrix();
//back
pushMatrix();
translate(thex-100,0,thez-40);
box(220, 500, -30);
popMatrix();
//middle side
for(int i=1;i<7;i++)
{
pushMatrix();
translate(thex-100,-250+71.5*i,thez+10);
box(220, 5, -100);
popMatrix();
}
//top
pushMatrix();
translate(thex-100,250,thez);
box(220, 10, -100);
popMatrix();
//block
pushMatrix();
translate(thex-100,-250,thez);
box(220, 10, -100);
popMatrix();
}
}
}
public void cameraUpdate(){
ty=constrain(dragMotionConstant, -100000, 500000);
//Drag-motion
if (lookMode == 1){
if(pmouseX > mouseX)
tx += dragMotionConstant;
else if (pmouseX < mouseX)
tx -= dragMotionConstant;
if(pmouseY > mouseY)
ty -= dragMotionConstant/1.5;
else if (pmouseY < mouseY)
ty += dragMotionConstant/1.5;
}
//Push-motion
else if (lookMode == 2){
if (mouseX > (width/2+pushMotionConstant))
tx += dragMotionConstant;
else if (mouseX < (width/2-pushMotionConstant))
tx -= dragMotionConstant;
if (mouseY > (height/2+pushMotionConstant))
ty += dragMotionConstant;
else if (mouseY < (height/2-pushMotionConstant))
ty -= dragMotionConstant;
}
//Push-motion V2 (Hopefully improved!)
else if (lookMode == 3){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if (abs(diffX) > pushMotionConstant)
tx += diffX/25;
if (abs(diffY) > pushMotionConstant)
ty += diffY/25;
}
//Push Motion V3 (For Camera-Mode 2)
else if (lookMode == 4){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
//println(diffX);
if (abs(diffX) > pushMotionConstant)
rotX += diffX/100;
if (abs(diffY) > pushMotionConstant)
rotY += diffY/100;//diffY/100;
}
//Push Motion V4.1 (Because it crashed and I lost V4.0 T.T
//Designed to work in cohesion with movement mode 2
else if (lookMode == 5){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if(abs(diffX) > stillBox){
xComp = tx - x;
zComp = tz - z;
angle = degrees(atan(xComp/zComp));
//---------DEBUG STUFF GOES HERE----------
//println("tx: " + tx);
//println("tz: " + tz);
// println("xC: " + xComp);
// println("zC: " + zComp);
// println("Angle: " +angle);
//--------------------------------------*/
if (angle < 45 && angle > -45 && zComp < 0)
tx += diffX/sensitivity;
else if (angle < 45 && angle > -45 && zComp > 0)
tx -= diffX/sensitivity;
//Left Sector
else if (angle > 45 && angle < 90 && xComp < 0 && zComp < 0)
tz -= diffX/sensitivity;
else if (angle >-90 && angle <-45 && xComp < 0 && zComp > 0)
tz -= diffX/sensitivity;
//Right Sector
else if (angle <-45 && angle >-90)
tz += diffX/sensitivity;
else if (angle < 90 && angle > 45 && xComp > 0 && zComp > 0)
tz += diffX/sensitivity;
}
if (abs(diffY) > stillBox)
ty += diffY/(sensitivity/1.5);
}
//Lookmode 4.2
//Using a more proper unit circle.
else if (lookMode == 6){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if(abs(diffX) > stillBox){
xComp = tx - x;
zComp = tz - z;
angle = correctAngle(xComp,zComp);
//---------DEBUG STUFF GOES HERE----------
// println("tx: " + tx);
// println("tz: " + tz);
// println("xC: " + xComp);
/// println("zC: " + zComp);
/// println("Angle: " +angle);
//--------------------------------------*/
//Looking 'forwards'
if ((angle >= 0 && angle < 45) || (angle > 315 && angle < 360))
tx += diffX/sensitivity;
//Looking 'left'
else if (angle > 45 && angle < 135)
tz += diffX/sensitivity;
//Looking 'back'
else if (angle > 135 && angle < 225)
tx -= diffX/sensitivity;
//Looking 'right'
else if (angle > 225 && angle < 315)
tz -= diffX/sensitivity;
}
if (abs(diffY) > stillBox)
ty += diffY/(sensitivity/1.5);
}
//Lookmode 7, trying to get rid of the slowdown in the corners with a sorta-buffer thing
else if (lookMode == 7){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if(abs(diffX) > stillBox){
xComp = tx - x;
zComp = tz - z;
angle = correctAngle(xComp,zComp);
//---------DEBUG STUFF GOES HERE----------
// println("tx: " + tx);
// println("tz: " + tz);
// println("xC: " + xComp);
// println("zC: " + zComp);
// println("Angle: " +angle);
//--------------------------------------*/
//Looking 'forwards'
if ((angle >= 0-camBuffer && angle < 45+camBuffer) || (angle > 315-camBuffer && angle < 360+camBuffer))
tx += diffX/sensitivity;
//Looking 'left'
else if (angle > 45-camBuffer && angle < 135+camBuffer)
tz += diffX/sensitivity;
//Looking 'back'
else if (angle > 135-camBuffer && angle < 225+camBuffer)
tx -= diffX/sensitivity;
//Looking 'right'
else if (angle > 225-camBuffer && angle < 315+camBuffer)
tz -= diffX/sensitivity;
}
if (abs(diffY) > stillBox)
ty += diffY/(sensitivity/1.5);
}
else if (lookMode == 8){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if(abs(diffX) > stillBox){
xComp = tx - x;
zComp = tz - z;
angle = correctAngle(xComp,zComp);
angle+= diffX/(sensitivity*10);
if(angle < 0)
angle += 360;
else if (angle >= 360)
angle -= 360;
float newXComp = cameraDistance * sin(radians(angle));
float newZComp = cameraDistance * cos(radians(angle));
tx = newXComp + x;
tz = -newZComp + z;
//---------DEBUG STUFF GOES HERE----------
/*println("tx: " + tx);
println("tz: " + tz);
println("xC: " + xComp);
println("NewXC: " + newXComp);
println("zC: " + zComp);
println("NewZC: " + newZComp);
println("Angle: " +angle);*/
//--------------------------------------*/
}
if (abs(diffY) > stillBox)
ty += diffY/(sensitivity/1.5);
}
}
public void locationUpdate(){
/*Old method==================================
if(keyPressed){
if (keyCode == UP || key == 'w'){
z-=10;
tz-=10;
}
else if (keyCode == DOWN || key == 's'){
tz+=10;
z+=10;
}
else if (keyCode == LEFT || key == 'a' ){
tx-=10;
x-=10;
}
else if (keyCode == RIGHT || key == 'd'){
tx+=10;
x+=10;
}
}
============================================*/
//Apply Movement
if(moveMode == 1){
z += moveZ;
tz += moveZ;
x += moveX;
tx += moveX;
}
else if(moveMode == 2){
if(moveUP){
z += zComp/movementSpeed;
tz+= zComp/movementSpeed;
x += xComp/movementSpeed;
tx+= xComp/movementSpeed;
}
else if(moveDOWN){
z -= zComp/movementSpeed;
tz-= zComp/movementSpeed;
x -= xComp/movementSpeed;
tx-= xComp/movementSpeed;
}
if (moveRIGHT){
z += xComp/movementSpeed;
tz+= xComp/movementSpeed;
x -= zComp/movementSpeed;
tx-= zComp/movementSpeed;
}
if (moveLEFT){
z -= xComp/movementSpeed;
tz-= xComp/movementSpeed;
x += zComp/movementSpeed;
tx+= zComp/movementSpeed;
}
}
//New method also uses keyPressed() and keyReleased()
// Scroll Down!
}
public void jumpManager(int magnitude){
/*
if(keyPressed && key == ' ' && canJump){
vY -= magnitude;
if(vY < -20)
canJump = false;
}
else*/ if (y < ground+standHeight)
vY ++;
else if (y >= ground+standHeight){
vY = 0;
y = ground + standHeight;
}
if((!canJump) && (!keyPressed)){
//println("Jump Reset!");
canJump = true;
}
y += vY;
}
public void keyPressed(){
if(keyCode == UP || key == 'w'){
moveZ = -10;
moveUP = true;
}
else if(keyCode == DOWN || key == 's'){
moveZ = 10;
moveDOWN = true;
}
else if(keyCode == LEFT || key == 'a'){
moveX = -10;
moveLEFT = true;
}
else if(keyCode == RIGHT || key == 'd'){
moveX = 10;
moveRIGHT = true;
}
if(key == 'm' && m==1){
m=0;
}
else if(key == 'm' && m==0){
if(key == '1')
{
}
rotateY(180);
fill(#EAFF0F);
textSize(50);
text("menu", x-100, y, z+300);
m=1;
}
}
public void keyReleased(){
if(keyCode == UP || key == 'w'){
moveUP = false;
moveZ = 0;
}
else if(keyCode == DOWN || key == 's'){
moveDOWN = false;
moveZ = 0;
}
else if(keyCode == LEFT || key == 'a'){
moveLEFT = false;
moveX = 0;
}
else if(keyCode == RIGHT || key == 'd'){
moveRIGHT = false;
moveX = 0;
}
}
void mousePressed()
{
}
public float correctAngle(float xc, float zc){
float newAngle = -degrees(atan(xc/zc));
if (xComp > 0 && zComp > 0)
newAngle = (90 + newAngle)+90;
else if (xComp < 0 && zComp > 0)
newAngle = newAngle + 180;
else if (xComp < 0 && zComp < 0)
newAngle = (90+ newAngle) + 270;
return newAngle;
}
People can use their first person view to walk the library.It is fine in java mode,but when I put it in java script mode,the view has problem.So , which part of my code has problems so that it can not run on website?
Thank you very much.