I have an image which moves horizontally with a given speed over a delta time(dt). But the problem is,the image doesn't bounces off when it reaches the end of the size of the world.How can i make the image bounces off backward so it would be kept inside the world?
Any help will do.
Here's what i've tried so far:
#Override
public void move(long dt)
{
// v = dx / dt
// dx m = v m/s . dt s
double dt_s = dt / 1e9;
double dx_m = speed * dt_s;
double left_wall = 0;
double right_wall = board.x1_world;
if (x <= right_wall)
{
x += dx_m;
if (x >= right_wall)
{
x = right_wall;
x *= -dx_m;
}
}
}
#Override
public void move(long dt)
{
double dt_s = dt / 1e9;
double dx_m = speed * dt_s;
double left_wall = 0;
double right_wall = board.x1_world;
x += dx_m;
if (x <= 0) speed *= -1.0;
if (x >= right_wall) speed *= -1.0;
}
When the x coordinate of your images reach an border, just change the orientation of the horizontal speed (multiply it for -1). But you should use an condition like this:
if (x >= (right_wall - width_of_image)) speed *= -1.0;
Instead of just x >= right_wall, because doing so, the image will bounce when it "touchs" the end of the world.
In addition to checking each end separately, as suggested by #Oscar, you may need to account for the image's finite width, as shown in this Subway simulation.
private boolean goleft=false;//keep direction
#Override
public void move(long dt)
{
// v = dx / dt
// dx m = v m/s . dt s
double dt_s = dt / 1e9;
double dx_m = speed * dt_s;
double left_wall = 0;
double right_wall = board.x1_world;
if(goleft)x += dx_m;
else x-= dx_m;
if (x >= right_wall)//touching 1 wall
{
x = right_wall;
x += dx_m;
goleft=true;
}else if(x<=left_wall){//touching the other wall
x = left_wall;
x += dx_m;
goleft=false;
}
}
Related
Hello this is actually my first question here.. I have been developing a opengl lwjgl game and I'm working on the entities class.I have accomplished to make an entity jump(ill use this for animals) but the "issue" (99.9% sure its my fault) is that each time the entity touches the terrain and jumps again the jump is higher as seen in the video I recorded this is the code for jump thz =D I just want the tree to move up always the same.
Video
double velocity = 0;
double initVelX;
double initVelZ;
double time = 0;
float x;
float y;
float z;
public void bounce() {
double initialVelocity = 0.1;
double speed = 1/2500.0;
if(time == 0) {
velocity += initialVelocity;
}
time += speed;
velocity = velocity - 9.8 * speed;
if(y + velocity < 0.1){
velocity *= -1;
}
y += velocity;
setPosition(new Vector3f(getPosition().x,y,getPosition().z));
}
Fixed it just had to do a simple line of code and it even has the speed fluctuations correct:
double velocity = 0;
double initVelX;
double initVelZ;
double time = 0;
float x;
float y;
float z;
public void bounce() {
double initialVelocity = 0.1;
double speed = 1/2500.0;
if(time == 0) {
velocity = initialVelocity;
}
time += speed;
velocity = velocity - 9.8 * speed;
if(y + velocity < 0.1){
velocity *= -1;
velocity = initialVelocity;
}
y += velocity;
setPosition(new Vector3f(getPosition().x,y,getPosition().z));
}
I think it will be one of these increment statements:
velocity += initialVelocity;
time += speed;
velocity *= -1;
y += velocity;
Do you want all of these to keep rising continually? Because that's what will happen.
Which part of your code calculates the height of the jump?
I am currently working on a 2D side scroller and have implemented the techniques use in this article for a grapple hook, and it works really well. My problem is I want my player to be able to swing around the rope a little bit to gain a bit of momentum, but currently I can't stop the player from moving all the way up to 90 degrees either side. What techniques can be applied to force this limit?
I have tried using a separate player speed for swinging but this only slows the process down I can still swing up to 90 deg each side.
Here's my update function in the player
public void update(float dt){
//handle friction and air resistance
if(dx !=0){
if(touchingGround) {
// apply friction
if (dx > 0) {
dx -= retardation;
} else {
dx += retardation;
}
} else {
//applied air resistance
if (dx > 0) {
dx -= airResistance;
} else {
dx += airResistance;
}
}
}
// handle gravity
dy -= Constants.GRAVITY * dt;
if(dy < -terminalVelocity){
dy = -terminalVelocity;
}
/*
Handle Player movement
*/
if(right){
if(dx <= maxSpeed){
dx += acceleration;
}
dx = maxSpeed;
}
if(left){
if(dx <= -maxSpeed){
dx -= acceleration;
}
dx = -maxSpeed;
}
if(isGrappling){
//If we collide with something we need to stop grappling
if(hasCollided){
isGrappling = false;
} else {
// This algorithm from here:
// http://gamedev.stackexchange.com/questions/61596/player-rope-swing
float currentD = (float) Math.sqrt(((grappleX - x) * (grappleX - x)) + ((grappleY - y) * (grappleY - y)));
float prevX = getX(), prevY = getY();
if (currentD > grappleRadius) {
Vector2 hookPos = new Vector2(grappleX, grappleY);
Vector2 testPos = (new Vector2(x, y).sub(hookPos)).nor();
y = (hookPos.y + testPos.y * grappleRadius);
x = (hookPos.x + testPos.x * grappleRadius);
// s = d / t
dx += (x - prevX) / dt;
dy += (y - prevY) / dt;
}
}
}
/*
Collision Detection, handle last always!
*/
float oldX = getX(), oldY = getY();
boolean collisionX = false, collisionY = false;
// move on x
x += dx * dt;
// calculate the increment for step in #collidesLeft() and #collidesRight()
increment = collisionLayer.getTileWidth();
increment = getWidth() < increment ? getWidth() / 2 : increment / 2;
if(dx < 0) // going left
collisionX = collidesLeft();
else if(dx > 0) // going right
collisionX = collidesRight();
// react to x collision
if(collisionX) {
setX(oldX);
dx = 0;
}
// move on y
y += dy * dt;
// calculate the increment for step in #collidesBottom() and #collidesTop()
increment = collisionLayer.getTileHeight();
increment = getHeight() < increment ? getHeight() / 2 : increment / 2;
if(dy < 0) {
touchingGround = collisionY = collidesBottom();
// we can only jump 2 times before we have to touch the floor again
if(collisionY){
numberOfJumps = 2;
}
} else if(dy > 0) {
collisionY = collidesTop();
}
// react to y collision
if(collisionY) {
setY(oldY);
dy = 0;
}
hasCollided = collisionX || collisionY;
}
As I am not using any physics engine I chose to just emulate the physics by limiting the angle at which the player can apply force to the swing.
// check if angle permits movement
if(grappleAngle < Math.PI/9 && grappleAngle > -Math.PI/9) {
// handle momentum gaining on rope
if (right) {
dx += swingAcceleration * dt;
}
if (left) {
dx -= swingAcceleration * dt;
}
}
So I am working on a blackjack game, I have wrote a render process which will render a card going out of the cards stack and sliding to the place where it shows all dealer's cards.
My method works fine, except one problem which I will elaborate:
Whenever Y coordinate reaches the target Y coordinate first, the sprite will only move on X-asis because it cant move Y anymore, instead of making a straight angle to the point.
So what it will do is move up diagonally and then instantly go to the right (in my case)
GIF:
(source: gyazo.com)
MP4 (choose mp4 in the (..) menu http://gyazo.com/bec6daadcb46bedc4777a3e4c5ff8c77)
As you can see, it does what I just said.
What did I do wrong? how can I make it motion in a straight angle to the target without going diagonal up and than turn right away?
My process code:
// If the target is on the right side of the start point
if (startPoint.getX() < endPoint.getX()) {
if (current.getX() < endPoint.getX()) {
current.x += moveSpeed;
if (current.getX() > endPoint.getX()) {
current.x = (int) endPoint.getX();
}
}
else {
xDone = true;
}
}
else {
if (current.getX() > endPoint.getX()) {
current.x -= moveSpeed;
if (current.getX() < endPoint.getX()) {
current.x = (int) endPoint.getX();
}
}
else {
xDone = true;
}
}
// Vise-versa
if (startPoint.getY() < endPoint.getY()) {
if (current.getY() < endPoint.getY()) {
current.y += moveSpeed;
if (current.getY() > endPoint.getY()) {
current.y = (int) endPoint.getY();
}
}
else {
yDone = true;
}
}
else {
if (current.getY() > endPoint.getY()) {
current.y -= moveSpeed;
if (current.getY() < endPoint.getY()) {
current.y = (int) endPoint.getY();
}
}
else {
yDone = true;
}
}
// Callback, dw about it
CardContainer.getCardSprite(CardContainer.SPECIAL, 0).drawSprite((int) current.getX(), (int) current.getY());
// Alert finished, in poisiuton
if (xDone && yDone) {
ch.submitCard(card);
}
current = current position
startPoint = the start point
endPoint = the end point
Thanks!
EDited code:
private void applyMovement(double alpha) {
double dx = endPoint.getX() - startPoint.getX();
double dy = endPoint.getY() - startPoint.getY();
this.current.setLocation(startPoint.getX() + alpha * dx, startPoint.getY() + alpha * dy);
}
public void process() {
double alpha = (double) stepsDone / distance;
applyMovement(alpha);
stepsDone++;
// Callback, dw about it
CardContainer.getCardSprite(CardContainer.SPECIAL, 0).drawSprite((int) current.getX(), (int) current.getY());
// Alert finished, in poisiuton
if (stepsDone >= distance) {
ch.submitCard(card);
}
}
Distance calculation:
this.distance = (int) start.distance(end);
Used Point2D distance method:
public double distance(Point2D pt) {
double px = pt.getX() - this.getX();
double py = pt.getY() - this.getY();
return Math.sqrt(px * px + py * py);
}
I would recommend to not use any form of "slope" in such a computation. You will run into problems when the difference in x-direction approaches zero, because then the slope will tend towards infinity.
Assuming that your points are Point2D.Double (or something similar - you should include this kind of information in your questions!), you can compute the movement as follows:
private Point2D.Double initial = ... // The initial position
private Point2D.Double current = ... // The current position
private Point2D.Double target = ... // The target position
void applyMovment(double alpha) {
double dx = target.getX() - initial.getX();
double dy = target.getY() - initial.getY();
current.x = initial.getX() + alpha * dx;
current.y = initial.getY() + alpha * dy;
}
The applyMovment method sketched here can be called with a double value between 0.0 and 1.0, where 0.0 corresponds to the initial position and 1.0 corresponds to the target position. This is just a Linear Interpolation.
So for example, when you have some sort of loop for the animation, you can use the method as follows:
int numberOfSteps = 10;
for (int i=0; i<=numberOfSteps; i++)
{
double alpha = (double)i / numberOfSteps;
applyMovement(alpha);
repaint();
}
This works for any arrangement of the start- and end points, without any sign- or direction issues. It just interpolates between the two positions.
Your calculation needs to be based upon moving the currentY and currentX along a specific line, not a specific set of intervals (moveSpeed). The formula for graphing points on a line is:
y = mx + b
Where x and y are the varying points, m is equal to the slope of the line, and b is what's called the y-intercept.
Your slope is calculated by the formula:
double slope = ((double) endPoint.getY() - startPoint.getY()) / ((double) endPoint.getX() - startPoint.getX());
And the Y intercept can be calculated by just plugging in a bunch of known values once you have them:
double yIntercept = (double) endPoint.getY() - (slope * endPoint.getX())
Then, just loop through the count of the difference in X:
for (int xVal = startPoint.getX(); xVal < endPoint.getX(); xVal++){
currentX = xVal;
currentY = (slope * xVal) + yIntercept;
}
And you should be good.
Warning: this is all off of the top of my head, I don't know if it'll compile.
private void gotoPos()
{
spaceX = x2 - x;
spaceY = y2 - y;
if (Math.abs(spaceX) >= Math.abs(spaceY)) {
xSpeed = Math.round(spaceX * (3/Math.abs(spaceX)));
ySpeed = Math.round(spaceY * (3/Math.abs(spaceX)));
}
With this code I want to move an object to the position x2 and y2. x and y is the current position of the object. spaceX is the space that is between the object and the x position it should go to. The same for spaceY.
But I don't want the object to move more than 3 Pixels per draw.
Example: object position: x = 35, y = 22
Point it should go to: x2 = 79, y2 = 46
space between them: spaceX = 79-35 = 44, spaceY = 46-22 = 24
spaceX is bigger then spaceY so:
xSpeed = 44 * (3/44) = 3, ySpeed = 24 * (3/44) = 1.63 = 2
But it does not work like this. When I start the app the object does not go to x2 and y2.
If I change
xSpeed = spaceX;
ySpeed = spaceY;
The object moves to the position but I do not want it to go there instantly
Complete Code:
public class Sprite
{
private boolean walking = true;
private int actionWalk = 0;
private Random rnd;
private int checkIfAction;
private int nextAction = 0;
static final private int BMP_COLUMNS = 4;
static final private int BMP_ROWS = 4;
private int[] DIRECTION_TO_SPRITE_SHEET = { 1, 0, 3, 2 };
public int x=-1;
private int y=-1;
public int xSpeed;
private int ySpeed;
private int width;
private int height;
private int bottomSpace;
private Bitmap bmp;
private GameView theGameView;
private int currentFrame=0;
private int x2, y2;
private boolean isTouched;
private int spaceX, spaceY;
D
public Sprite(GameView theGameView, Bitmap bmp)
{
this.theGameView = theGameView;
this.bmp = bmp;
this.width = bmp.getWidth() / BMP_COLUMNS;
this.height = bmp.getHeight() / BMP_ROWS;
rnd = new Random();
xSpeed = 0;
ySpeed = 0;
}
public void shareTouch(float xTouch, float yTouch)
{
x2 = (int) xTouch;
y2 = (int) yTouch;
isTouched = true;
}
private void gotoPos()
{
spaceX = x2 - x;
spaceY = y2 - y;
if (Math.abs(spaceX) >= Math.abs(spaceY)) {
xSpeed = Math.round(spaceX * (3/Math.abs(spaceX)));
ySpeed = Math.round(spaceY * (3/Math.abs(spaceX)));
}
else {
xSpeed = spaceX;
ySpeed = spaceY;
}
}
D
private void bounceOff()
{
bottomSpace = theGameView.getHeight() - y;
if (x > theGameView.getWidth() - (width * theGameView.getDensity()) - xSpeed - bottomSpace / 2 || x + xSpeed < bottomSpace / 2)
{
xSpeed = -xSpeed;
}
x = x + xSpeed;
if (y > theGameView.getHeight() - (height * theGameView.getDensity()) - ySpeed || y + ySpeed < theGameView.getHeight() / 2)
{
ySpeed = -ySpeed;
}
y = y + ySpeed;
currentFrame = ++currentFrame % BMP_COLUMNS;
}
d
public void onDraw(Canvas canvas)
{
if (x == -1)
{
x = (theGameView.getWidth() / 2);
y = (theGameView.getHeight() / 2 + theGameView.getHeight() / 4);
}
if (isTouched == true)
{
gotoPos();
}
/* if (nextAction == 100)
{
action();
nextAction = 0;
}
nextAction += 1;*/
bounceOff();
int sourceX, sourceY;
if (walking == true)
{
sourceX = currentFrame * width;
}
else
{
sourceX = 0;
}
sourceY = getAnimationRow() * height;
Rect source = new Rect(sourceX, sourceY, sourceX + width, sourceY + height);
Rect destine = new Rect(x, y, (int) (x + (width * theGameView.getDensity())), (int) (y + (height * theGameView.getDensity())));
canvas.drawBitmap(bmp, source, destine, null);
}
d
private int getAnimationRow()
{
double directionDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2);
int spriteDir = (int) Math.round(directionDouble) % BMP_ROWS;
return DIRECTION_TO_SPRITE_SHEET[spriteDir];
}
}
Simple problem: you use integer arithmetic and don't understand this:
spaceX * (3/Math.abs(spaceX))
The result will be 0 in nearly all cases as 3/x with x > 3 is 0 all the time.
To make your program working use either floating point arithmetic or rewrite your formulas to work as expected.
To use floating point arithetic you have to change to
spaceX * (3.0/Math.abs(spaceX))
assuming that you variable spaceX is also floating point.
Also you can use
(spaceX * 3) / Math.abs(spaceX)
if you want to stay with integers (what I suppose).
Given points a Vector2d(x, y) and b Vector2d(x2, y2)-
Create a vector V from a to b by subtracting b from a as you did. Normalize vector V into a unit vector and multiply it with the distance you want. Then add the resulting vector to point a.
On update:
a.add(b.subtract(a).norm().multiply(d));
Depending on your vector implementation, modify properly the above pseudo code.
There is a logical fallacy in your code: what if Math.abs(spaceX) < Math.abs(spaceY))? Then your object would not move at all.
What you calculate, 'x-distance / y-distance', is usually considered angle, not speed. Speed is 'distance / time'. You can calculate the distance, and you should decide on a reasonable speed for your object. Since you know your fps -- 20 --, you can then calculate how many pixels your object needs to move in each frame.
so I've been trying to program the mandelbrot set in java, I know the code isn't very optimized but i've just started out doing this.
The idea is that when i click a pixel it will put that pixel in the center (that represents a certain complex number) and calculate the set around it. This works at the beginning but if i zoom in it will start to behave weird. I'm guessing it's either my midX, midY or the display function that's weird but i've been looking at it for a long time and can't figure it out, would appreciate some help.
class set {
DotWindow w;
int[][] arrayColor;
int max = 100;
Grayscale gray;
double zoom = 1.1;
double midX = -0.5;
double midY = 0;
public static void main(String[] args) {
new set().run();
}
void run() {
setup();
runLoop();
}
void runLoop() {
int x;
int y;
while (true) {
GameEvent event = w.getNextEvent();
switch (event.getKind()) {
case GameEvent.KEY_PRESSED:
int key = event.getKey();
if (key == 43) {
zoom = zoom * 1.1;
} else if (key == 45) {
zoom = zoom / 1.1;
}
display();
break;
case GameEvent.MOUSE_CLICKED:
midX = midX - (1 - event.getX() / 250.0);
midY = midY - (1 - event.getY() / 250.0);
System.out.println(midX);
display();
break;
}
}
}
void setup() {
w = new DotWindow(500, 500, 1);
w.checkMouse(true, false, false, false, false);
w.checkKeys(true, false, false);
arrayColor = new int[500][500];
zoom = zoom / 1.1;
display();
}
int calculate(double re, double im) {
double Zre = 0;
double Zim = 0;
double Zim2 = 0;
double Zre2 = 0;
int iterations = 0;
for (int k = 0; k < max; k++) {
if (Zre2 + Zim2 > 4.0) {
return k;
}
Zim2 = Zim * Zim;
Zre2 = Zre * Zre;
Zim = 2.0 * Zre * Zim + im;
Zre = Zre2 - Zim2 + re;
iterations = k;
}
return iterations;
}
void display() {
for (double y = 0; y < 500; y++) {
for (double x = 0; x < 500; x++) {
double value = calculate((midX - (1 - x / 250) / zoom),
(midY - (1 - y / 250) / zoom));
if (value == 99) {
w.setDot((int) x, (int) y, Color.BLACK);
} else {
w.setDot((int) x, (int) y, gray = new Grayscale(
255 - (int) value * 2));
}
}
}
}
}
case GameEvent.MOUSE_CLICKED:
midX = midX - (1 - event.getX() / 250.0)/zoom;
midY = midY - (1 - event.getY() / 250.0)/zoom;
System.out.println(midX);
display();
You've already zoomed in, say to 10x, but you change central coordinates not regarding the zoom value.