I am trying to use a character controller to move around a platform in my project. I have typed out and debugged my code, and am still having trouble figuring out what is wrong.
Camera script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mouseschtuff : MonoBehaviour
{
public float mouseSpeed = 100f;
public Transform playerBody;
float xRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSpeed * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSpeed * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
If I don’t make the camera(Main Camera) A child of the player body, then the horizontal movement does not work at all, but in the video i watched to help me, it worked just fine.
Movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ActualMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 10f;
public float gravity = -10f;
public float jumpHeight = 5f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0){
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetButton("Jump") && isGrounded){
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
I can move around just fine, but for some reason, If i turn my head (Camera as PlayerBody’s child) and push “w” i move wherever forward is as a global coordinate. I have no trouble with my gravity nor my jumping mechanism