我有一个有点(阅读:非常)损坏的命中墙功能,我看不出我做错了什么



好吧,现在我正在研究一个基于布朗运动的小游戏,我正在研究粒子的撞墙函数,但它不起作用。基本上,我用弧度来表达粒子的方向,每当它碰到墙时,我都会在方向上添加Pi弧度来翻转它,但由于某种原因,它要么没有被调用,要么不起作用。这些是我的守则,欢迎任何建议。

import java.awt.*;

public class Particle implements Actor {
protected double xPos;
protected double yPos;
protected Velocity v;
protected Color hue;
protected boolean needsUpdate;
public Particle(){
    this((Math.random()*500),(Math.random()*500),new Velocity((int)(Math.random()*500),(Math.random()*Velocity.TAU)));
}
public Particle(double x, double y, Velocity vel){
    xPos=x;
    yPos=y;
    v=vel;
    hue=Color.red;
    needsUpdate=false;
}
public void draw(Graphics g) {
    g.setColor(hue);
    g.fillOval((int)xPos, (int)yPos, 16, 16);
}
public void act() {
    xPos+=v.getSlopefromDirection();
    yPos+=1;
}
public void onHitWall(int dir) {
    v.setDirection((v.getDirection()+Math.PI)%(Math.PI*2));     
}
public void onHitOther(Actor other) {
}
public boolean canCollide() {
    return true;
}
public int getLeftX() {
    return (int)xPos;
}
public int getRightX() {
    return (int)xPos+4;
}
public int getTopY() {
    return (int)yPos;
}
public int getBottomY() {
    return (int)yPos+4;
}

}

这就是我用来显示它的类:

import java.awt.*;
import java.util.*;
import javax.swing.*;
import static java.lang.System.out;
public class Feild extends JFrame{
protected ArrayList<Actor> actors;
private final int size=500;
protected Thread th;
public Feild(ArrayList<Actor> a){
    super("A Brownian Love Story");
    setSize(size, size);
    actors=a;
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    th = new Thread();
    while(true){
        paint(getGraphics());
    }
}
public void paint(Graphics g){
    super.paint(g);
    //g.fillRect(0, 0, 500, 500);
    for(int i=0;i<actors.size();i++){
        if(actors.get(i).getLeftX()<=0)
            actors.get(i).onHitWall(1);
        if(actors.get(i).getRightX()>=500)
            actors.get(i).onHitWall(2);
        if(actors.get(i).getTopY()<=0)
            actors.get(i).onHitWall(1);
        if(actors.get(i).getBottomY()>=500)
            actors.get(i).onHitWall(2);
        actors.get(i).act();
        actors.get(i).draw(g);
    }
    for(int i=0;i<1000;i++){out.println(i);}
}

}

所以我试着在表演后将paint函数更改为检查碰撞,但看起来onHitWall仍然被跳过了,尽管在输入打印语句后它并没有被跳过。

问题是,粒子会移动,直到它们撞到墙上,然后下次通过外观时,它们仍然在墙上,再次转身,然后继续进入墙上。

如果在执行act()函数后检查冲突,这应该可以解决问题。

他们会走进墙,看到自己在墙里,然后转身。在下一个循环中,它们将移回墙外,并继续。

相关内容

最新更新