I'm working on a game for a game jam, and can't get my collision system to work. The way it's supposed to work is when an the player intersects with a wall hitbox it moves the player towards the last position until it no longer intersects. This doesn't work though, this is the code:`
while(worldBox.intersects((Rectangle2D) Player.entity)) {
if(offsetX - lastX > 0) offsetX --;
if(offsetX - lastX < 0) offsetX ++;
if(offsetY - lastY > 0) offsetY --;
if(offsetY - lastY < 0) offsetY ++;
makeWorldHitBox();
}
` and here is the link to the github repo: https://github.com/DJPretzel-bit64/LemonRunner.git
I tried changing sines and offsets, nothing worked
Related
so recently, we've been assigned to code multiple circles that act like robots in a GUI interface. Basically, a robot simulator.
I've got the code to spawn in multiple circles that can act like robots.
This is my current code for detecting wall collision between the robot and the end of the square:
private void checkCollisions(double maxX, double maxY) {
for (ListIterator<Ball> slowIt = balls.listIterator(); slowIt.hasNext();) {
Ball b1 = slowIt.next();
// check wall collisions:
double xVel = b1.getXVelocity();
double yVel = b1.getYVelocity();
if ((b1.getCenterX() - b1.getRadius() <= 0 && xVel < 0)
|| (b1.getCenterX() + b1.getRadius() >= maxX && xVel > 0)) {
b1.setXVelocity(-xVel);
}
if ((b1.getCenterY() - b1.getRadius() <= 0 && yVel < 0)
|| (b1.getCenterY() + b1.getRadius() >= maxY && yVel > 0)) {
b1.setYVelocity(-yVel);
}
for (ListIterator<Ball> fastIt = balls.listIterator(slowIt.nextIndex()); fastIt.hasNext();) {
Ball b2 = fastIt.next();
final double deltaX = b2.getCenterX() - b1.getCenterX() ;
final double deltaY = b2.getCenterY() - b1.getCenterY() ;
if (colliding(b1, b2, deltaX, deltaY)) {
bounce(b1, b2, deltaX, deltaY);
}
}
}
}
The
b1.setXVelocity(-xVel);
b1.setYVelocity(-yVel);
are the main bits that make the circle bounce back from the wall. However, instead of this, I want the ball to detect the wall and rotate 90 degrees rather than bounce back form the wall like a bouncing ball.
Any help will be fully appreciated or a working piece of code that ca do this for me. I have an AraryList of all the balls called 'balls'.
If needed, I can give source code.
This is what I have so far. But I need each ball to have a sensor attached to them detecting if there a wall ahead.
https://i.stack.imgur.com/XsQvX.png
Assuming you have just square walls:
If the ball hits the right wall for example, you want to remove all x velocity, and then add either positive or negative velocity.
The issue with this is that the robot will end up just going around the outside edges of the map.
I'm making a racing car game where my racing course is similar to a rectangular donut. In the middle of the rectangle I have another smaller rectangle which acts as a wall. I'm trying to add collision detection to my inside wall so that my cars will collide with the inside walls. Below are some basic measurements of the inside wall as well as a picture showing a concept of the track:
-Translated x from 14 to 18 units is the width of the rectangle.
-Translate y from -60 to 60 units is the total length of the rectangle.
My problem currently is if I try making the cars collide when the x position hits the wall at 14 units from the origin (or with y), it creates collision for the entire x or y line. So for example, once I hit the wall that's located 14 units in the x direction it doesn't let me pass if I were to reach that location at one of the turning points in the race course. I'm trying the following at the moment.
void checkColl(){
if (posX < -14){
velocityX *= -1 //bounce off the wall on the far left side of the picture
}
if (posX > 48){
velocityX *= -1 //bounce off wall on far right
}
if ((posY > 60 || posY < -60) && (posX > 14 && posX < 18)){ //bounce off the rectangle in middle of race course
velocityY = velocityY * -1;
velocityX = velocityX * -1;
}
}
The check for the y coordinate is broken. Try this:
if ((posY > -60 && posY < 60) && (posX > 14 && posX < 18)){
//bounce off the rectangle in middle of race course
This defines points within the black rectangle - the hole of the "doughnut".
The bitmap A has a position which is its X/Y position is static, bitmap B is moving bitmap which moves from the bottom of the screen to where ever the user touches on screen. When the moving bitmap reaches the static bitmap however it is not recognized as a collision, the moving bitmap uses float which i round off and the static bitmap uses int. Below is a snippet of code, I want to figure out what is needed to be changed for my bitmaps crossing paths to be considered a collision
canvas.drawBitmap(rock2, 70, 32, null);
//this is where it checks to see if the moving bitmaps y coordinate is matched to the Y coordinate of the static bitmap
if(canvas.getHeight() - Math.round(animY*-1) == (canvas.getHeight() - (canvas.getHeight()-32))){
Log.d("ALERT", "COLLIDE");
}
//the Y value is *-1 because the moving bitmap is starting from the bottom of the screen so this converts the value to positive value
I wonder if my calculations are off, or I am going about this collision the wrong way. Below is my movement code snippet
//UP Y ANIMATION
if(animY*-1 < canvas.getHeight() && !bumpY){
animY += speedY;
//IF ROCK IS NOT AT EXTREME LEFT OR EXTREME RIGHT KEEP ON TRACK
if(animX < (canvas.getWidth()/2) || animX*-1 < (canvas.getWidth()/2) && !bumpX){
animX += speedX;
//IF ROCK HITS EDGE LEFT/RIGHT RETURN TO SENDER (INDICATE BUMP)
if(animX*-1 > (canvas.getWidth()/2) - rock.getWidth()/2 || animX > (canvas.getWidth()/2) - rock.getWidth()/2){
bumpX = true;
bumpY = true;
}
}
//IF Y HITS TOP OF SCREEN
if(animY*-1 > canvas.getHeight()){
bumpY = true;
}
}
//DOWN Y ANIMATION
if(animY < 0 && bumpY){
//REVERSE DIRECTION OF Y
animY -= speedY;
//IF ROCK HITS TOP OR SIDE REVERSE X DIRECTION
if(bumpX || bumpY)
animX -= speedX;
//IF AT STARTING POINT
if(animY > 0){
bumpY = false;
bumpX = false;
}
}
//in an ontouch method where the X and Y values are calculated
case MotionEvent.ACTION_UP:
finalX = event.getX() - (cross.getWidth() / 2);
finalY = event.getY() - (cross.getHeight() / 2);
moveToX = finalX - startX;
moveToY = finalY - startY;
speedX = moveToX / 50;
speedY = moveToY / 50;
break;
Any tips would be appreciated, thank you.
sorry if this is a dumb answer, but should your check be:
if(canvas.getHeight() - Math.round(animY*-1) >= (canvas.getHeight() - (canvas.getHeight()-32))){
instead? (change the "==" to ">=" ) otherwise you are only checking for when the rock lands EXACTLY on (canvas.getheight -32), rather than checking past it
I wrote a program to solve the following:
Implement a diffusion limited aggregation simulation on a toroid plane where seeds are randomly created, and particles move randomly. they move if they particles do not land near a seed or a particle. where user inputs seeds (red pixels), particles (black pixels), steps (no or iterations), plane size.
My code is very slow. How can I make it faster?
I randomly created x and y coordinates and drew red pixels (seeds), then randomly created x and y for black pixels (particles), if a black pixel lands where there is a red or black pixel it can stay, otherwise it moves randomly again until there are no more particles . If the pixel lands out of borders like x > border then x=0; if x <1 then x= border. The same for y.
This just means that if it lands on the border I move it to the opposite border. Then checks for the neighboring pixels again. I have an outer loop to create the seeds, and inner loop for the particles. In the inner loop I check for the x,y positions:
//Place, move, and "stick" the particles; stop if either steps or particles = 0
for (int p = 0; p < particles; p++) {
for (int s = 0; s < steps; s++) {
if (xPos > image.getWidth() ) {
do something
}
else if (xPos < 1) {
do something
}
if (yPos > image.getHeight() - 2) {
do something
}
else if (yPos < 1) {
do something
}
else if (xPos > image.getWidth() && yPos > image.getHeight()) {
do something
}
else if (xPos < 1 && yPos < 1) {
do something
}
//If the surrounding pixels' color is not white, make that particle stick.
if (moveValid()) {
image.setRGB(xPos, yPos, 0xFF000000);
}
//Otherwise, move in a random direction
else {
if(xPos == 1 && image.getRGB(size - 2, yPos) != 0xFFFFFFFF){
draw(xPos,yPos);
}
else if(xPos == size - 2 && image.getRGB(1,yPos) != 0xFFFFFFFF){
draw(xPos,yPos);
}
if(yPos == 1 && image.getRGB(xPos, size - 2) != 0xFFFFFFFF){
draw(xPos,yPos);
}
else if(yPos == size - 2 && image.getRGB(xPos,1) != 0xFFFFFFFF){
draw(xPos,yPos);
}
else {
move();
}
}
}
//Regenerate random x and y positions for the next particle
xPos = random.nextInt(size);
yPos = random.nextInt(size);
}
Although the implementation of draw() is not shown, it looks like you're updating a BufferedImage and then rendering it.
The first step is always to profile your existing code, looking for easily implemented optimizations.
The second step is sometimes to set aside the existing code and try a different approach.
You may be able to leverage the Mode-View-Controller pattern, outlined here and discussed here. In particular, let your DLA model evolve on a background thread at full speed, while updating your view at a more sustainable rate. This article suggests several approaches to synchronization and includes a related example that uses javax.swing.Timer to pace the updates.
This is probably a really basic problem but I can't seem to find any other articles on it.
Anyway, I have written a small bouncing ball program in Java to try and expand my basic skills. The program is just a simple bouncing ball that will drop and hopefully bounce for a while. The original program worked fine but now I have tried to add gravity into the program. The gravity actually works fine for a while but then once the bounces get really small the animation becomes erratic for a very short time then the position of the ball just constantly decreases. I've tried to figure out the problem but I just can't see it. Any help would be most welcome.
public final class Ball extends Rectangle {
float xspeed = 1.0f; float yspeed = 1.0f; float gravity = 0.4f;
public Ball(float x, float y, float width, float height) {
super(x, y, width, height);
}
public void update(){
yspeed += gravity;
move(xspeed, yspeed);
if(getX() < 0){
xspeed = 1;
}
if(getX() + getWidth() > 320){
xspeed = -1;
}
if(getY() < 0){
yspeed = 1;
}
if(getY() + getHeight() > 200 && yspeed > 0){
yspeed *= -0.98f;
}
if(getY() + getHeight() > 200 && yspeed < 0){
yspeed *= 0.98f;
}
}
public void move(float x, float y){
this.setX(getX()+x);
this.setY(getY()+y);
}
}
EDIT: Thanks that seems to have sorted the erratic movement. I'm still struggling to see how I can stop my ball moving down when it has stopped bouncing. Right now it will move stop bouncing then continue moving down passed the "floor". I think it's to do with my yspeed += gravity line. I just can't see how I'd go about stopping the movement down.
When you do
yspeed += gravity;
you are assuming that the ball has space move through a distance dx = v_i * t + 1/2 (-g) t^2. When you are very near the floor this may not be true. It fail if:
You are near enough the the floor and moving down
You are very near the floor and have low velocity (like when the ball has lost most of it's energy)
This bug causes your simulation to stop conserving energy, resulting in the erratic behavior you see at low amplitude.
You can reduce the problem by using smaller time steps, and you can get rid of it outright if you do test computation to notice when you're out of room and to select a safe time step for that iteration (i.e. always use your default unless there is a problem, then calculate the best time step).
However, the basic approximation you're using here has other problems as well. Look in any numeric analysis text for a discussion of solving differential equations numerically.
First things first: setting y-speed to 1 when you bounce on the top of the window is not correct, you should set yspeed to -yspeed (but if you start within the borders, it should never bounce up to the top anyway).
Secondly, your multiply by -0.981 when bouncing on the bottom is okay but I'm concerned with the constant 0.4 gravity being added to yspeed every iteration. I think that's what is causing you wiggles at the bottom since you do the move before checking which can result in the ball dropping below ground level.
I would try ensuring the the y value can never go below ground level by replacing the move with:
if (getY() + getHeight() + yspeed > 200) {
move(xspeed, 200 - getY() - getHeight());
} else {
move(xspeed, yspeed);
}
The problem is that when the bounces get really small, the
yspeed *= -0.981;
line will get called in short succession. The ball will go below the bottom, start coming back up, but still be below the bottom (because 0.981 < 1.0) eventually, and it will behave eradically. Here's how you fix it:
if(getY() + getHeight() > 200){
yspeed *= -0.981;
setY(400 - getY() - getHeight()); // I believe this is right.
}
By fixing the position, you won't alternate between decreasing and increasing as quickly and won't get stuck in the situation where it is always decreasing because it is always below the bounds.
[EDIT: I think I misunderstood, so this probably isn't much use :) ]
if(getY() + getHeight() > 200){
yspeed *= -0.981;
}
You're negating the vertical velocity on every update. I'd probably try handling gravity in update-sized slices. Assuming you're doing 30 updates per second (for 30fps), maybe something like
// Define some constants
SecondsPerUpdate = (1.0f / 30);
AccelDueToGravity = 0.981;
if(getY() + getHeight() > 200){
yspeed -= (AccelDueToGravity * SecondsPerUpdate);
}
I suspect it's because when the ball bounces, it will actually be slightly below the "ground", and at low speeds, it won't move back above the ground in one tick - so the next update() will see it still below the ground, and bounce again - but downwards this time, so the cycle continues.
You need to move the ball back up to ground level when it bounces, something like this:
if(getY() + getHeight() > 200){
yspeed *= -0.981;
setY(200 - getHeight());
}