前言
相信大多数人(新手)在写Unity2D的游戏中都会遇到角色翻转问题,本次针对此问题提出两个方法以便游戏制作和后续学习!
此处先准备好了一个角色和场景!
如图:
方法一
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
private float movementInputDirection;//移动输入方向
private bool isFacingRight = true;
private Rigidbody2D rb;
public float movementSpeed = 10f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
CheckInpute();
CheckMovementDirection();
}
private void FixedUpdate()
{
ApplyMovement();
}
private void CheckMovementDirection()
{
if (isFacingRight && movementInputDirection < 0)
{
Flip();
}else if(!isFacingRight && movementInputDirection > 0)
{
Flip();
}
}
private void CheckInpute()
{
movementInputDirection = Input.GetAxisRaw("Horizontal");
}
private void ApplyMovement()
{
rb.velocity = new Vector2(movementInputDirection * movementSpeed, rb.velocity.y);
}
private void Flip()
{
isFacingRight = !isFacingRight;
transform.Rotate(0.0f, 180.0f, 0.0f);
}
}
方法二
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
private float movementInputDirection;//移动输入方向
private bool isFacingRight = true;
private Rigidbody2D rb;
public float movementSpeed = 10f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
CheckInpute();
CheckMovementDirection();
}
private void FixedUpdate()
{
ApplyMovement();
}
private void CheckMovementDirection()
{
if (isFacingRight && mousePos.x < transform.position.x)//if mouse position is on the left of the player and player facing right then face left
{
Flip();
}else if(!isFacingRight && mousePos.x > transform.position.x))//if mouse position is on the right of the player and player facing left then face right
{
Flip();
}
}
private void CheckInpute()
{
movementInputDirection = Input.GetAxisRaw("Horizontal");
}
private void ApplyMovement()
{
rb.velocity = new Vector2(movementInputDirection * movementSpeed, rb.velocity.y);
}
private void Flip()
{
isFacingRight = !isFacingRight;
transform.Rotate(0.0f, 180.0f, 0.0f);
}
}
本次通过鼠标的移动来实现角色的翻转
总结
这里提供了两种2D角色在平台上进行翻转的代码,以便大家学习和运用。第一种是通过wasd进行按压使角色移动转向,第二种是通过鼠标在角色的左/右方向进行转向(可适用2D枪战)。
最后,大家有更好的方法,欢迎大家留言分享。