01_Pong/Player.cs

29 lines
961 B
C#

using Godot;
public partial class Player : CharacterBody2D {
[Export] private int playerNumber;
[Export] private int speed = 10000;
public override void _PhysicsProcess(double delta) {
Vector2 velocity = Velocity;
if (Input.IsAnythingPressed()) {
if (Input.IsActionPressed("Player1Up") && playerNumber == 1) velocity.Y = Mathf.RoundToInt(-speed * delta);
else if (Input.IsActionPressed("Player1Down") && playerNumber == 1) velocity.Y = Mathf.RoundToInt(speed * delta);
if (Input.IsActionPressed("Player2Up") && playerNumber == 2) velocity.Y = Mathf.RoundToInt(-speed * delta);
else if (Input.IsActionPressed("Player2Down") && playerNumber == 2) velocity.Y = Mathf.RoundToInt(speed * delta);
Velocity = velocity;
}
else {
Velocity = Vector2.Zero;
}
KinematicCollision2D collision = MoveAndCollide(velocity * (float)delta);
if (collision?.GetCollider() is StaticBody2D staticBody2D) {
Velocity = Vector2.Zero;
}
}
}