Pong/Scripts/Objects/Paddle.cs
Fries 604d79e654 the paddle can now scale to the resolution
i added a GameArea class which makes it easier to operate on in coordinates bounds with the GameCoordinate struct wrapper which does calculations for me. the GameArea class also has a normalization system which is how the ScalingManager can teleport items in bounds to relatively the same place when resized.

it took quite a while to get the paddle to teleport. looks like im supposed to modify the position inside IntegrateForces instead of PhysicsProcess which is my mistake.
2023-05-23 00:21:54 -07:00

66 lines
1.5 KiB
C#

using Pong.Scripts.Managers;
namespace Pong.Scripts.Objects;
public partial class Paddle : RigidBody2D
{
[Export] private double _moveSpeed;
private double _verticalInput;
private readonly StringName _paddleUp = "paddle_up";
private readonly StringName _paddleDown = "paddle_down";
private ScalingManager _scalingManager;
private bool _canMove = true;
private Vector2 _originalPosition;
private Vector2? _newPosition;
/// <summary>
/// property that multiples the moveSpeed by the <see cref="Constants.Meter">Meter</see> constant.
/// </summary>
private double MoveSpeed => _moveSpeed * Constants.Meter;
public override void _EnterTree()
{
SetNotifyTransform(true);
SetNotifyLocalTransform(true);
_scalingManager = GetNode<ScalingManager>("../ScalingManager");
_scalingManager.NewPaddlePosition += (_, vector2) => _newPosition = vector2;
}
public override void _Process(double delta)
{
_verticalInput = GetVerticalInput();
}
public override void _IntegrateForces(PhysicsDirectBodyState2D state)
{
if (_newPosition.HasValue)
{
state.Transform = new Transform2D(0, _newPosition.Value);
_newPosition = null;
}
state.LinearVelocity = Vector2.Up * MoveSpeed * _verticalInput;
}
/// <summary>
/// a method that returns a number that represents input on the vertical axis.
/// </summary>
/// <returns>1 for up, -1 for down, 0 for nothing.</returns>
private double GetVerticalInput()
{
if (Input.IsActionPressed(_paddleUp))
{
return 1;
}
if (Input.IsActionPressed(_paddleDown))
{
return -1;
}
return 0;
}
}