【发布时间】:2019-05-23 20:48:15
【问题描述】:
我希望我的球员在比赛开始后不再轮换。我在脚本和约束中也冻结了旋转,但是玩家在向前移动时仍然会旋转。我能做些什么 ? (我有一个 fps 和一个角色控制器)。我也有一个带有按钮的画布来控制左,对吧?我应该将刚体或玩家脚本放在角色对象中(我制作了一个包含角色和相机的玩家游戏对象)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
public float playerSpeed = 1500;
public float directionalSpeed = 20;
private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
}
// Update is called once per frame
void Update()
{
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER
float moveHorizontal = Input.GetAxis("Horizontal");
transform.position = Vector3.Lerp(gameObject.transform.position, new Vector3(Mathf.Clamp(gameObject.transform.position.x + moveHorizontal, -2.5f, 2.5f), gameObject.transform.position.y, gameObject.transform.position.z), directionalSpeed * Time.deltaTime);
#endif
GetComponent<Rigidbody>().velocity = Vector3.forward * playerSpeed * Time.deltaTime;
transform.Rotate(Vector3.right * GetComponent<Rigidbody>().velocity.z / 3);
//MOBILE CONTROLS
Vector2 touch = Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0, 0, 10f));
if (Input.touchCount > 0)
{
transform.position = new Vector3(touch.x, transform.position.y, transform.position.z);
}
}
public void MoveLeft()
{
rb.velocity = new Vector2(-playerSpeed, rb.velocity.y);
}
public void MoveRight ()
{
rb.velocity = new Vector2(playerSpeed, rb.velocity.y);
}
public void StopMoving()
{
rb.velocity = new Vector2(0f, rb.velocity.y);
}
void DetectInput()
{
float x = Input.GetAxisRaw("Horizontal");
if (x > 0 )
{
MoveRight();
}
else if ( x < 0)
{
MoveLeft();
}
else
{
StopMoving();
}
}
}
【问题讨论】:
-
当你冻结刚体旋转时,它只会在物理交互方面冻结它,使用 transform.Rotate 方法仍然会旋转你的对象,而不管你的约束如何。
transform.Rotate(Vector3.right * GetComponent<Rigidbody>().velocity.z / 3); -
如果您删除
Rotate,它将停止旋转 -
将
rb = GetComponent<Rigidbody>();放在Start()的开头,然后不再调用GetComponent<Rigidbody>。只需使用rb。经常拨打GetComponent会减慢速度。 -
如果我想让我的角色在向左移动的同时自动向左旋转可以吗?
-
你能改写一下吗?我想我不明白你在问什么。