您现在的位置是:首页 >学无止境 >请用unity生成一个控制2D刚体移动的代码,要求左右键控制转向,前后控制前进后退的网站首页学无止境
请用unity生成一个控制2D刚体移动的代码,要求左右键控制转向,前后控制前进后退的
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
public float rotationSpeed = 100.0f;
private Rigidbody2D rb;
private Vector2 moveVelocity;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput.normalized * speed;
if (moveInput.x > 0)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, 0, -90), rotationSpeed * Time.deltaTime);
}
else if (moveInput.x < 0)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, 0, 90), rotationSpeed * Time.deltaTime);
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
}
}