Unity 2d player movement with smooth rotation.

Code

PlayerController.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private float _horizontalInput, _verticalInput;
    private Vector3 _direction;
    
    private PlayerTankMovement actionScript;
    
    // Start is called before the first frame update
    void Start() => actionScript = GetComponent<PlayerTankMovement>();

    // Update is called once per frame
    void Update()
    {
        GetInput();
        actionScript.RotateTankBody(_horizontalInput);
        actionScript.RotateTankTurret(_direction);
    }

    private void FixedUpdate()
    {
        actionScript.MovePlayer(_verticalInput);
    }

    private void GetInput()
    {
        _horizontalInput = Input.GetAxisRaw("Horizontal");
        _verticalInput = Input.GetAxisRaw("Vertical");
        _direction = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,
            Camera.main.nearClipPlane));
    }
}

PlayerTankMovement.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerTankMovement : MonoBehaviour
{
    [SerializeField] private float movementSpeed = 2, rotationSpeedTank = 180, rotationSpeedTurret = 150;

    private Transform tankBody, tankTurret;
    private Rigidbody2D _rigidbody2D;
    
    // Start is called before the first frame update
    void Start()
    {
        tankBody = transform.Find("Chassie");
        tankTurret = transform.Find("Turret");

        _rigidbody2D = GetComponent<Rigidbody2D>();
    }
    
    public void MovePlayer(float inputValue) 
        => _rigidbody2D.velocity = tankBody.right * movementSpeed * Mathf.Clamp01(inputValue);

    public void RotateTankBody(float inputValue)
    {
        float rotation = -inputValue * rotationSpeedTank;
        tankBody.Rotate(Vector3.forward * rotation * Time.deltaTime);
    }

    public void RotateTankTurret(Vector3 endPoint)
    {
        Quaternion desiredRotation = Quaternion.LookRotation(Vector3.forward, endPoint - tankTurret.position);
        desiredRotation = Quaternion.Euler(0, 0, desiredRotation.eulerAngles.z + 90);
        tankTurret.rotation = Quaternion.RotateTowards(tankTurret.rotation, desiredRotation, rotationSpeedTurret * Time.deltaTime);
    }
}

实现效果

posted @ 2022-12-29 14:58  yassine  阅读(209)  评论(0编辑  收藏  举报