2D平面游戏角色移动代码(PC端)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class controler : MonoBehaviour
{
private Rigidbody2D rigidbody2D;
private Animator animator;
private float speed = 20f;
void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
void Update()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
if (horizontalInput != 0)
{
animator.SetFloat("Horizontal", horizontalInput);
animator.SetFloat("Vertical", 0);
}
if (verticalInput != 0)
{
animator.SetFloat("Vertical", verticalInput);
animator.SetFloat("Horizontal", 0);
}
Vector2 dir = new Vector2(horizontalInput, verticalInput);
animator.SetFloat("Speed", dir.magnitude);
Vector2 moveDirection = Vector2.zero;
if (horizontalInput != 0)
{
moveDirection.x = horizontalInput;
}
if (verticalInput != 0)
{
moveDirection.y = verticalInput;
}
if ((Mathf.Abs(horizontalInput) + Mathf.Abs(verticalInput)) == 1)
{
Vector2 newPosition = rigidbody2D.position + (moveDirection * speed * Time.deltaTime);
rigidbody2D.MovePosition(newPosition);
}
}
}
2D平面游戏角色移动代码(移动端)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MobilePlayerController : MonoBehaviour
{
private Rigidbody2D rigidbody2D;
private Animator animator;
[SerializeField]
private float speed = 3f;
private float horizontalInput = 0;
private float verticalInput = 0;
void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
void Update()
{
if (horizontalInput != 0)
{
animator.SetFloat("Horizontal", horizontalInput);
animator.SetFloat("Vertical", 0);
}
if (verticalInput != 0)
{
animator.SetFloat("Vertical", verticalInput);
animator.SetFloat("Horizontal", 0);
}
Vector2 dir = new Vector2(horizontalInput, verticalInput);
animator.SetFloat("Speed", dir.magnitude);
MovePlayer(dir);
}
public void onPointerUp()
{
verticalInput = 1;
}
public void onPointerDown()
{
verticalInput = -1;
}
public void onPointerLeft()
{
horizontalInput = -1;
}
public void onPointerRight()
{
horizontalInput = 1;
}
public void onIdle()
{
horizontalInput = 0;
verticalInput = 0;
}
private void MovePlayer(Vector2 direction)
{
Vector2 newPosition = rigidbody2D.position + (direction * speed * Time.deltaTime);
rigidbody2D.MovePosition(newPosition);
}
}