Question by
$$anonymous$$ · Jan 14, 2020 at 08:17 PM ·
movementvelocityaxiscontrolridgidbody
Can't move player with this code why?,I cannot move my player with this code why?
using UnityEngine;
public class PlayerMovement : MonoBehaviour { private float sensitivity = 150f; public Rigidbody rb; private bool grounded;
public Transform playerBody;
public Transform groundChecker;
public Camera playerCam;
public LayerMask whatIsGround;
public float moveSpeed = 10f;
public float jumpCooldown = 1f;
private float xRotation;
bool readyToJump;
void Start()
{
rb = GetComponent<Rigidbody>();
Cursor.lockState = CursorLockMode.Locked;
readyToJump = true;
}
void Update()
{
Look();
Movement();
}
private void Movement()
{
grounded = Physics.OverlapSphere(groundChecker.position, 0.5f, whatIsGround).Length > 0;
print(grounded);
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
bool jumping = Input.GetButton("Jump");
Vector2 mag = FindVelRelativeToLook();
float xMag = mag.x, yMag = mag.y;
CounterMovement(x, y, mag);
if (x > 0 && xMag > 5) x = 0;
if (x < 0 && xMag > -5) x = 0;
if (y > 0 && yMag > 5) y = 0;
if (y < 0 && yMag > -5) y = 0;
rb.AddForce(transform.forward * y * moveSpeed * Time.deltaTime);
rb.AddForce(transform.right * x * moveSpeed * Time.deltaTime);
if (grounded && readyToJump && jumping)
{
readyToJump = false;
rb.AddForce(Vector3.up * 200);
Invoke(nameof(ResetJump), jumpCooldown);
}
}
private void ResetJump()
{
readyToJump = true;
}
private void Look()
{
float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
playerCam.transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
}
private void CounterMovement(float x, float y, Vector2 mag)
{
if (!grounded) return;
float threshold = 0.3f;
float multiplier = 0.3f;
print(mag.x);
if(x == 0)
{
rb.AddForce(moveSpeed * transform.right * Time.deltaTime * -mag.x * multiplier);
}
if(y == 0)
{
rb.AddForce(moveSpeed * transform.forward * Time.deltaTime * -mag.y * multiplier);
}
}
private Vector2 FindVelRelativeToLook()
{
float lookAngle = transform.eulerAngles.y;
float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
float u = Mathf.DeltaAngle(lookAngle, moveAngle);
float v = 90 - u;
float magnitue = rb.velocity.magnitude;
float yMag = magnitue * Mathf.Cos(u * Mathf.Deg2Rad);
float xMag = magnitue * Mathf.Cos(v * Mathf.Deg2Rad);
return new Vector2(xMag, yMag);
}
}
Comment
Your answer
Follow this Question
Related Questions
Gyroscope Controls for FPS 0 Answers
Move NPC on triggerEnter 0 Answers
Please help me to move my player a fixed distance 1 Answer
Pressing both vertical and horizontal axis slows down my move speed 0 Answers
Don't moving diagonal 1 Answer