# Problem mit Kollisionsabfrage der NPC



## TheBeerfall (29. Jan 2014)

Guten Tag Java-Forum Gemeinde,
ein Freund und ich haben ein Problem bei der Kollisionsabfrage eines Gegners. Die von der Spielfigur klappt wunderbar.

Manchmal glitcht der Gegner einfach in die Objekte, oder springt durch die Welt, obwohl er die Kollision wahrnimmt.  Und ein weiteres kleines Problem ist, dass wenn er zwischen zwei Objekten hängt nur noch hin und her rennt und nicht mehr zufällig seinen Weg wählt.

Falls jemand für das Problem eine Lösung weiß oder Verbesserungen für den Code weiß, wären wir sehr froh darüber... Wir hängen mittlerweile schon Stunden an diesem Fehler... Und wissen einfach nicht, wieso es beim Spieler ohne Probleme klappt und beim Gegner nicht.

PS: Ich weiß nicht ob ich die Bilder hochladen soll oder nicht. Zur Not einfach selbst Bilder einfügen. Sie sollten 50x50 Pixel groß sein.

Code:
Klasse GameApplet

```
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JApplet;

public class GameApplet extends JApplet implements KeyListener {
	GameObject player, speedGIF, background;
    private BufferedImage offscreen;
    private final int width=800;
    private final int height=600;
    
    int flagRight = 0;
    int flagLeft = 0;
    int flagUp = 0;
    int flagDown = 0;
    boolean flagBackground = false;
    
    private final int OFFSET = 0;
    private final int SPACE = 50;
    private ArrayList <GameObject> rocks = new ArrayList<GameObject>();
    private ArrayList <GameObject> trees = new ArrayList<GameObject>();
    private ArrayList <GameObject> waters = new ArrayList<GameObject>();
    private ArrayList <GameObject> chests = new ArrayList<GameObject>();
    private ArrayList <Person> 	   enemies = new ArrayList<Person>();
    private ArrayList <GameObject> world;
    
    GameObject rock;
    GameObject tree;
    GameObject water;
    GameObject chest;
    Person enemy;
    
    Image backgroundImg = new ImageIcon("wiesefinal.gif").getImage();
    Image rockImg = new ImageIcon( "rock.gif" ).getImage();
    Image treeImg = new ImageIcon( "treefinal.gif" ).getImage();
    Image waterImg = new ImageIcon( "water.gif" ).getImage();
    Image enemyImg = new ImageIcon( "nachtelfrightwalk.gif" ).getImage();
    Image chestImg = new ImageIcon( "Schatzkiste.gif" ).getImage();
    
    private String level =		//16 Spalten  || 12 Reihen
        "################\n"			//# = rock
      + "###             \n"			//$ = tree
      + "##  $$... @     \n"			//. = water
      + "##  $$#...    ##\n"			//@ = player
      + "##$  $###.   ###\n"			//! = chest
      + "##$$ ######  ###\n"			//, = enemy
      + "#!           ###\n"
      + "#  $  $       ##\n"
      + "#        ,     #\n"
      + "#          ....#\n"
      + "#$$$   $$  ....#\n"
      + "################\n";
  
    int isOn = 0;
    AudioClip audioClip;
public void init() {
	 
	  audioClip = getAudioClip(getCodeBase(), "Runescape.wav");
	  audioClip.play();
	  
        int x = OFFSET;
        int y = OFFSET;
        
        speedGIF = new GameObject(getImage("smooth.gif"),0,0);
        background = new GameObject(getImage("800x600.jpg"),0,0); //Bild für die Breite und Höhe
       
        for (int i = 0; i < level.length(); i++) {

            char item = level.charAt(i);

            if (item == '\n') {
                y += SPACE;

                x = OFFSET;
            } else if (item == '#') {
                rock = new GameObject(rockImg, x, y);
                rocks.add(rock);
                x += SPACE;
            } else if (item == '$') {
                tree = new GameObject(treeImg, x, y);
                trees.add(tree);
                x += SPACE;
            } else if (item == '.') {
                water = new GameObject(waterImg, x, y);
                waters.add(water);
                x += SPACE;
            } else if (item == '@') {
                player = new Person(getImage("fassfinal.gif"),x, y);
                x += SPACE;
            } else if (item == '!') {
                chest = new GameObject(chestImg,x, y);
                chests.add(chest);
                x += SPACE;
            } else if (item == ',') {
                enemy = new Person(enemyImg,x, y);
                enemies.add(enemy);
                x += SPACE;
            } else if (item == ' ') {
                x += SPACE;
            }
            
            setSize(width,height);
        	setFocusable(true);
        	addKeyListener(this);
        }
    }
public void paint(Graphics g) {
	world = new ArrayList<GameObject>();
	world.addAll(rocks);
	world.addAll(trees);
	world.addAll(waters);
	world.addAll(chests);
	
	Graphics buffer = getGraphicsBuffer();
	moveGameObjects();
	speedGIF.draw(buffer,this);
	
	int x = 0;
	int y = 0;

		for(int yi = 0; yi<12; yi++){
			x = 0;
			for(int xi = 0; xi<16; xi++){
				buffer.drawImage(backgroundImg, x, y, this);
				x+= 50;
			}
			y+= 50;
		}

	for (int i = 0; i < world.size(); i++) {
	   GameObject item = (GameObject) world.get(i);
	   item.draw(buffer, this);
	}
	for (int i = 0; i < enemies.size(); i++) {
		   Person ene = (Person) enemies.get(i);
		   ene.draw(buffer, this);
		}
	player.draw(buffer, this);
	g.drawImage(offscreen, 0, 0, this);
	buffer.dispose();
}

    public void moveGameObjects() {
    	player.move();
    	if (!player.collidingWith(background)) player.undoMove();
    	for(GameObject obj : world) {
    		if (player.collidingWith(obj)) player.undoMove();
    	}
    	for(Person pers : enemies) {
    		if (player.collidingWith(pers)) player.undoMove();
    	}
    	
    	for(int i=0; i<enemies.size();i++) {
    		Person collidePerson = (Person) enemies.get(i);
    		collidePerson.algoMove();
    		if (!collidePerson.collidingWith(background))
    			collidePerson.mirrorMove(); //Funktioniert
    		while(!collidePerson.collidingWith(background)){
				collidePerson.algoMove();
			}
    		
    		if (collidePerson.collidingWith(player)){
    			collidePerson.mirrorMove();
    			while(collidePerson.collidingWith(player)){
    				collidePerson.algoMove();
    			}
			}
    		for (GameObject obj : world) {
    			if (collidePerson.collidingWith(obj)){ 
    				collidePerson.mirrorMove();
    				while(collidePerson.collidingWith(obj)){
    					collidePerson.algoMove();
    				}
    			}
    		}
    	}
    }
  
	public void keyPressed(KeyEvent event) {
		int key = event.getKeyCode(); 
		switch (key) {
		case KeyEvent.VK_RIGHT: flagRight = 1;
								if(flagRight == 1 && flagUp == 1){
			 						player.vx = 10; player.vy = -10; break;
								} 
								else if(flagRight == 1 && flagDown == 1){
			 						player.vx = 10; player.vy = 10; break;
								}
								player.vx = 10; player.vy = 0; break;
								
		case KeyEvent.VK_LEFT: flagLeft = 1;
							   if(flagLeft == 1 && flagUp == 1){
								   player.vx = -10; player.vy = -10; break;
							   }
							   else if(flagLeft == 1 && flagDown == 1){
								   player.vx = -10; player.vy = 10; break;
							   }
							   player.vx = -10; player.vy = 0; break;
							   
		case KeyEvent.VK_UP: flagUp = 1;
							 if(flagRight == 1 && flagUp == 1){
								 player.vx = 10; player.vy = -10; break;
							 }
							 else if(flagLeft == 1 && flagUp == 1){
								 player.vx = -10; player.vy = -10; break;
							 }
							 player.vx = 0; player.vy = -10; break;
							 
		case KeyEvent.VK_DOWN: flagDown = 1;
							   if(flagRight == 1 && flagDown == 1){
								   player.vx = 10; player.vy = 10; break;
							   }
							   else if(flagLeft == 1 && flagDown == 1){
								   player.vx = -10; player.vy = 10; break;
							   }
							   player.vx = 0; player.vy = 10; break;
							   
		case KeyEvent.VK_ENTER: System.exit(0); break;	
		}
	}
	
	

	public void keyReleased(KeyEvent event) {
		int key = event.getKeyCode(); 
		switch (key) {	
		case KeyEvent.VK_RIGHT: flagRight = 0;
								if(flagRight == 0 && flagUp == 1){
									player.vx = 0; player.vy = -10; break;
								}
								else if(flagRight == 0 && flagDown == 1){
									player.vx = 0; player.vy = 10; break;
								}
								player.vx = 0; player.vy = 0; break;
								
		case KeyEvent.VK_LEFT:  flagLeft = 0;
								if(flagLeft == 0 && flagUp == 1){
									player.vx = 0; player.vy = -10; break;
								}
								else if(flagLeft == 0 && flagDown == 1){
									player.vx = 0; player.vy = 10; break;
								}
								player.vx = 0; player.vy = 0; break;
								
		case KeyEvent.VK_UP: 	flagUp = 0;
								if(flagRight == 1 && flagUp == 0){
									player.vx = 10; player.vy = 0; break;
								}
								else if(flagLeft == 1 && flagUp == 0){
									player.vx = -10; player.vy = 0; break;
								}
								player.vx = 0; player.vy = 0; break;
								
		case KeyEvent.VK_DOWN: 	flagDown = 0;
								if(flagRight == 1 && flagDown == 0){
									player.vx = 10; player.vy = 0; break;
								}
								else if(flagLeft == 1 && flagDown == 0){
									player.vx = -10; player.vy = 0; break;
								}
								player.vx = 0; player.vy = 0; break;
								
		}
		
	}
	public void keyTyped(KeyEvent event) { }    

	
	/**
	 * Hier folgen (technische) Hilfsmethoden zum störungsfreien
	 * Puffern und Laden der Grafiken.
	 */
	
    private Graphics getGraphicsBuffer() {
    	int width = getWidth();
    	int height = getHeight();
		if (offscreen == null || offscreen.getWidth() != width || offscreen.getHeight() != height) {
            offscreen = (BufferedImage)createImage(width,height);
        } 
    	return offscreen.createGraphics();
    }
    
	private Image getImage(String name) {
        URL url = GameApplet.class.getResource(name);
        Image img = null;
        try {
        	img = getToolkit().getImage(url);
            MediaTracker tracker = new MediaTracker(this);
            tracker.addImage(img, 0);
            tracker.waitForAll();
        } catch (Exception e) {
        	System.err.println("Could not load image "+name);
        	img = createImage(100,100);
        } 
        return img;
    } 
}
```
Klasse GameObject

```
import java.awt.Image;

import java.awt.*;
import java.awt.image.*;

public class GameObject {

	Image image;
	int x, y, vx, vy; 
	int width, height; 
	
	public GameObject(){;}
	
	public GameObject(Image image, int x, int y) {
		this.image = image;
		this.x = x;
		this.y = y;
	}
	
	public GameObject(Image image, int x, int y, int vx, int vy) {
		this.image = image;
		this.x = x;
		this.y = y;
		this.vx = vx;
		this.vy = vy;
	}
	
	public void move() {
		x += vx;
		y += vy;
	}
	
	public void undoMove() {
		x -= vx;
		y -= vy;
	}
	
	public boolean collidingWith(GameObject obj) {
		this.setBoundingBox();
		obj.setBoundingBox();
		int distx = (x-(obj.x+obj.width))*((x+width)-obj.x);
		int disty = (y-(obj.y+obj.height))*((y+height)-obj.y);
		if (distx<0 && disty<0) {
			return true;
		} else {
			return false;
		}
	}
	
	public void setBoundingBox() {
		width = image.getWidth(null);
		height = image.getHeight(null);
	}
	
	public void draw(Graphics graphics, ImageObserver observer) {
		graphics.drawImage(image,x,y,observer);
	}
}
```
Klasse Person

```
import java.awt.Image;
import java.util.ArrayList;
import java.util.Random;


public class Person extends GameObject{
	
	public Person(Image img, int x, int y){
		image = img;
		super.x = x;
		super.y = y;
	}
	
	int lifePoints;
	int hitStrength;
	float speed;

	private int random(int max){
		Random r = new Random();
		int rInt = r.nextInt(max);
		return rInt;
	}

	int moveCount = 0;
	int rnd;
	
	public void algoMove() {
		this.move();
		if(moveCount == 7){
			moveCount = 0;
		}
		
			rnd = random(4);
		
			if(moveCount == 0){
			switch (rnd) {
			case 0:
				this.vx = 10;
				this.vy = 0;
				moveCount =1;
				break;
			case 1:
				this.vx = -10;
				this.vy = 0;
				moveCount =1;
				break;
			case 2:
				this.vx = 0;
				this.vy = -10;
				moveCount =1;
				break;
			case 3:
				this.vx = 0;
				this.vy = 10;
				moveCount =1;
				break;
			}
		}
		moveCount++;
		
		
	}

	public void mirrorMove() {
		moveCount = 1;
		vx = vx * -1;
		vy = vy * -1;
	}

	}
```


----------



## TheBeerfall (6. Feb 2014)

Kann gelöscht werden.


----------

