Files
SMIMS_2026_2/SMIMS-Game/Player.java
T
Jonas 9e35cc9ebb Player Movement:
A - links
D - rechts
Leertaste - Springen
2026-09-15 09:57:01 +02:00

75 lines
1.6 KiB
Java

import greenfoot.*;
public class Player extends Actor
{
private int speed = 4;
private int jumpStrength = 12;
private int gravity = 1;
private int verticalSpeed = 0;
private boolean onGround = false;
public void act()
{
moveLeftAndRight();
jump();
fall();
}
// Bewegung nach links und rechts
private void moveLeftAndRight()
{
if (Greenfoot.isKeyDown("a"))
{
setLocation(getX() - speed, getY());
}
if (Greenfoot.isKeyDown("d"))
{
setLocation(getX() + speed, getY());
}
}
// Springen
private void jump()
{
if (Greenfoot.isKeyDown("space") && onGround)
{
verticalSpeed = -jumpStrength;
onGround = false;
}
}
// Schwerkraft und Boden-Kollision
private void fall()
{
verticalSpeed += gravity;
int newY = getY() + verticalSpeed;
// Prüfen, ob wir auf Ground landen
setLocation(getX(), newY);
Actor ground = getOneIntersectingObject(Ground.class);
if (ground != null)
{
// Wenn wir fallen, stehen wir auf dem Ground
if (verticalSpeed >= 0)
{
int groundTop = ground.getY() - ground.getImage().getHeight() / 2;
int characterHalfHeight = getImage().getHeight() / 2;
setLocation(getX(), groundTop - characterHalfHeight);
verticalSpeed = 0;
onGround = true;
}
}
else
{
onGround = false;
}
}
}