0

好的,现在我正在开发一个基于布朗运动的小型 derp-ish 游戏,并且我正在研究粒子的碰撞墙功能,但它不起作用。基本上,我用弧度表示粒子的方向,每当它撞到墙上时,我都会在方向上添加 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);}
}



}

所以我尝试将绘制功能更改为在执行后检查碰撞,它仍然看起来像 onHitWall 被跳过,即使在放入打印语句之后它不是。

4

1 回答 1

1

你遇到的问题是你的粒子会一直移动直到它们撞到墙,然后当你下一次查看时,它们仍然会在墙上,再次转身,然后继续进入墙内。

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

他们会走进墙里,看到他们在墙里,然后转身。下一个循环,他们将移出墙壁,继续前进。

于 2012-02-19T03:04:16.530 回答