Hi guys!
I’m currently playing around with java game development a bit.
I usually only write Servers in Java, so this is my first graphical application I am working on.
I learned the basics of how game update and render loops work, and got everything running smoothly so far.
There’s just one problem I came across:
Since I don’t use any framework (I love doing things on my own) I do not have the slightest idea of how I should implement a Platformer movement system.
My current approach looks like this:
// Pseudocode!
if (detectCollision(x, y + verticalVelocity) {
// Moves this instance to the floor
setToGround();
} else {
computeVelocity();
y += verticalVelocity;
}
if (detectCollision(x + horizontalVelocity, y) {
// Moves this instance to the wall
stopMovement();
} else {
computeMovement();
x += horizontalVelocity;
}
So what I’m basically doing is to iterate over a List of Blocks which define the collision in the level when detecting collisions.
As long as I don’t use walls which stop the horizontal movement of the player, everything works just fine.
But as soon as I move against a wall, everything goes foobar. I guess that’s because my collision detection is not entirely right:
//Actual code
public int detectCollision(Model model, int offX, int offY)
{
int colliding = 0;
int mTop = (int) (y + offY);
int mBot = (int) (y + height + offY);
int mRight = (int) (x + width + offX);
int mLeft = (int) (x + offX);
int oTop = (int) (model.y);
int oBot = (int) (model.y + model.height);
int oRight = (int) (model.x + model.width);
int oLeft = (int) (model.x);
int mMidX = (int) (x + (width / 2) + offX);
int mMidY = (int) (y + (height / 2) + offY);
if ((mRight >= oLeft) && (mLeft <= oRight)) {
if ((mBot >= oTop) && (mBot <= oBot)) {
colliding += 8;
}
if ((mTop <= oBot) && (mTop >= oTop)) {
colliding += 2;
}
}
if ((mBot >= oTop) && (mTop <= oBot)) {
if ((mRight >= oLeft) && (mRight <= oRight)) {
colliding += 1;
}
if ((mLeft <= oRight) && (mLeft >= oLeft)) {
colliding += 4;
}
}
return colliding;
}
What this basically does is returning a number from which I can read WHERE the collision is happening exactly.
Since the feedback is binary, there only is one possible combination for each situation.
This way, I can check if the instance is straight below (e.g. 8, in this case) my entity.
Anyway, this does not seem to work right.
So, my question is: Am I doing this right? Should I just continue optimising this simple JnR engine or am I doing it completely wrong?
If so, can anyone tell me a simple mechanic of how to do that right?
P.S. Sorry if this question was asked already, I used this forum’s search function but could not find any fitting topic.