我正在开发我的微游戏项目,其中涉及自上而下的第三人称射击游戏运动。有图就更容易解释了。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
public class EntityController : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] private float maxAccelTime = 2;
[SerializeField] private Camera currentCam;
[SerializeField] private Rigidbody2D currentPlayer;
private Vector2 cursorPos;
private Vector2 lookDir;
private float lookAngle;
private float accelTime, accelMultipier;
private float dragMultipier;
void Start()
{
accelTime = 0;
accelMultipier = 15;
dragMultipier = 10;
}
// Update is called once per frame
void Update()
{
//Control Movement Button
MovementController();
//Control Attack Button
AttackController();
}
private void MovementController()
{
//Control speed of the player. Player will get faster as long as they pressing the button and not stop moving immediately when stop pressing.
InitiateAceleration();
//Control look direction and movement of the player.
InitiateMovement();
}
private void AttackController()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//Initiate Attack on Mouse Direction
}
}
private void InitiateMovement()
{
//Control look direction of the player.
cursorPos = currentCam.ScreenToWorldPoint(Input.mousePosition);
lookDir = cursorPos - currentPlayer.position;
lookAngle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
//Control movement direction of the player.
currentPlayer.transform.Translate(Vector2.right * Input.GetAxis("Horizontal") * accelTime * accelMultipier * Time.deltaTime);
currentPlayer.transform.Translate(Vector2.up * Input.GetAxis("Vertical") * accelTime * accelMultipier * Time.deltaTime);
currentPlayer.rotation = lookAngle;
}
private void InitiateAceleration()
{
if (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)
{
if (accelTime < maxAccelTime)
{
accelTime += Time.deltaTime;
}
}
else
{
if (accelTime > 0)
{
accelTime -= (Time.deltaTime * dragMultipier);
}
}
}
}
我尝试设定一个条件,如果lookDir.x > 0且lookDir.y > 0,玩家就会移动(我认为晃动是由于当玩家移动非常靠近光标时的位置问题)。没用。
Transform.Translate
有一个可选的最后一个参数Space relativeTo
,默认情况下在本地空间移动(Space.Self
)!
为了在世界空间中应用平移,您需要传入
Space.World
作为附加的最后一个参数。