Hey all,
I’m currently creating a first person controller which will be used on a ring world (like this), but i’ve got a problem.
When I’m keeping the camera looking out of the ring world, the character moves fine, but once I look towards it, he starts rotating sideways. I believe it’s because of the script rotating the player along the Z-axis in local space instead of world space, but i’m not really sure.
Here’s my first person movement controller:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6;
public Rigidbody rb;
public GameObject center;
void FixedUpdate()
{
//Rotate player towards center pivot
Vector3 relativePos = center.transform.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(center.transform.forward, relativePos);
transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, rotation.eulerAngles.z);
//Debug stuff
Debug.DrawRay(transform.position, relativePos, Color.green);
//Move player based on current rotation of player
Vector3 fwrd = Input.GetAxis("Vertical") * transform.forward * Time.deltaTime * speed;
Vector3 rght = Input.GetAxis("Horizontal") * transform.right * Time.deltaTime * speed;
rb.GetComponent<Rigidbody>().velocity = fwrd + rght;
}
}
Here’s my camera movement script, if it’s necessary:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float mouseSensitivity = 100f;
public float xRotation = 0f;
public float speed = 5;
public Transform playerBody;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
Here’s a video.
Where’s the problem?