I'm making a (simple) game in java and found JavaFX.
At the moment I'm trying to get jumping functionality, with interaction with other objects.
I've gotten to the point where I have a jump that works, but it occasionally still passes through or around obstacles.
Hoping that someone who has experience with this will see this, or someone will be able to direct me to a relevant post (whether it be in javafx or other language).
import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Rectangle;
import javafx.animation.Timeline;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.KeyCode;
import javafx.animation.KeyFrame;
var posx = 50.0;
var posy = 400.0;
var nextposx = 0.0;
var nextposy = 0.0;
var jump = false;
var yVel = 100.0;
var yAcc = -9.8;
var downKey = false;
var upKey = false;
var leftKey = false;
var rightKey = false;
var obstacles = [
Rectangle { x: 50 y: 100 width: 100 height: 100 stroke: Color.RED }
];
var rect = Rectangle {
focusTraversable: true;
x: bind posx
y: bind posy
width: 40;
height: 40;
fill: RadialGradient {
stops: [
Stop {
color: Color.web("#80CAFA")
offset: 0
}
Stop {
color: Color.web("#1F6592")
offset: 1
}
]
}
onKeyPressed: function(e: KeyEvent): Void {
if (e.code == KeyCode.VK_UP) {
upKey = true;
} else if (e.code == KeyCode.VK_DOWN) {
downKey = true;
} else if (e.code == KeyCode.VK_LEFT) {
leftKey = true;
} else if (e.code == KeyCode.VK_RIGHT) {
rightKey = true;
} else if (e.code == KeyCode.VK_SPACE) {
yVel = 50;
jump = true;
}
}
onKeyReleased: function(e: KeyEvent): Void {
if (e.code == KeyCode.VK_UP) {
upKey = false;
} else if (e.code == KeyCode.VK_DOWN) {
downKey = false;
} else if (e.code == KeyCode.VK_LEFT) {
leftKey = false;
} else if (e.code == KeyCode.VK_RIGHT) {
rightKey = false;
}
}
}
var logics = Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames: KeyFrame {
time: 1s / 10
action: function() {
nextposx = posx;
nextposy = posy;
if (downKey) {
nextposy += 10;
}
if (upKey) {
nextposy -= 10;
}
if (leftKey) {
nextposx -= 10;
}
if (rightKey) {
nextposx += 10;
}
if (jump) {
println(jump);
nextposy -= yVel;
yVel = yVel + yAcc;
// if (nextposy - yVel <= 0) {
// nextposy -= yVel;
// yVel = yVel + yAcc;
// }
if (nextposy - yVel >= 500) {
nextposy = 500;
jump = false;
println(jump);
}
}
for (obst in obstacles) {
if (obst.boundsInParent.intersects(nextposx + 10, nextposy + 10, rect.width - 20, rect.height - 20)) {
return;
}
}
posx = nextposx;
if (nextposy <= 500) {
posy = nextposy;
}
}
}
}
logics.play();
Stage {
title: "Rect Jump!"
scene: Scene {
width: 200
height: 600
content: [obstacles, rect]
}
}
Help and comments appreciated


Sign In
Create Account

Back to top









