TopDownPlayerController.cs
using System.Linq;
using Sandbox;
using Sandbox.Citizen;
[Title( "Top Down Player Controller" )]
public class TopDownPlayerController : Component
{
[Property] public CharacterController CharacterController { get; set; }
[Property] public CitizenAnimationHelper AnimationHelper { get; set; }
[Property] public float WalkSpeed { get; set; } = 198f;
[Property] public float RunSpeed { get; set; } = 320f;
[Property] public float CameraDistance { get; set; } = 600f;
protected override void OnUpdate()
{
}
protected override void OnFixedUpdate()
{
base.OnFixedUpdate();
MovementInput();
UpdateAnimations();
}
protected override void OnPreRender()
{
//UpdateCamera();
}
private void MovementInput()
{
if (CharacterController is null) return;
Angles currentAngles = Transform.Rotation.Angles();
Vector3 analogMove = Input.AnalogMove;
float speed = Input.Down("Run") ? RunSpeed : WalkSpeed;
Vector3 wishVelocity = new Vector3(-analogMove.y, analogMove.x, analogMove.z).Normal * speed;
if (!wishVelocity.IsNearlyZero())
{
currentAngles.yaw = Rotation.LookAt(wishVelocity).Angles().yaw;
Transform.Rotation = Rotation.From(currentAngles);
}
if (!CharacterController.IsOnGround) {
wishVelocity += Scene.PhysicsWorld.Gravity;
}
CharacterController.Velocity = wishVelocity;
CharacterController.Move();
Transform.Rotation = currentAngles;
}
private void UpdateAnimations()
{
if (AnimationHelper is null) return;
AnimationHelper.WithVelocity(CharacterController.Velocity);
}
private void UpdateCamera()
{
CameraComponent camera = Scene.GetAllComponents<CameraComponent>().Where( x => x.IsMainCamera ).FirstOrDefault();
if ( camera is null || CharacterController is null ) return;
Vector3 characterPostion = CharacterController.Transform.Position;
Vector3 newCameraPosition = new Vector3(characterPostion.x, characterPostion.y, characterPostion.z + CharacterController.Height + CameraDistance);
camera.Transform.Position = newCameraPosition;
}
}