Player movement script like in FPS, Unity3d - c#

I have 2 scripts, which make player move like in the FPS game. But it don't move to that direction, to which player are looking - it always move to the same direction, regardless of the direction of the camera..
mouselook.cs
float yRotation;
float xRotation;
float lookSensitivity = 5;
float currentXRotation;
float currentYRotation;
float yRotationV;
float xRotationV;
float lookSmoothnes = 0.1f;
void Update ()
{
yRotation += Input.GetAxis("Mouse X") * lookSensitivity;
xRotation -= Input.GetAxis("Mouse Y") * lookSensitivity;
xRotation = Mathf.Clamp(xRotation, -80, 100);
currentXRotation = Mathf.SmoothDamp(currentXRotation, xRotation, ref xRotationV, lookSmoothnes);
currentYRotation = Mathf.SmoothDamp(currentYRotation, yRotation, ref yRotationV, lookSmoothnes);
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
}
playermovement.cs
public float walkSpeed = 6.0F;
public float jumpSpeed = 8.0F;
public float runSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= walkSpeed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}

make your mouse look like this
float lookSensitivity = 5;
float mouseX,mouseY;
public Transform playerBody;
float xRotation = 0f;
void Update ()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSentivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSentivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
save this and Drag your Player from hierarchy to the camera script playerBody.

Doesn't it need like a requirecomponentTypeof or something like that

Related

When look up my character moves forwards in unity

I am using this movement code with a box collider in unity (I am quite a beginner)
public class Movement : MonoBehaviour
{
public float speed = 10.0f;
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
transform.Translate(new Vector3(horizontalInput, 0, verticalInput) * Time.deltaTime * speed);
And this mouselook code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mouselook : MonoBehaviour
{
public float sensitivity = 100.0f;
public float clampAngle = 80.0f;
private float rotX = 0.0f;
private float rotY = 0.0f;
void Start()
{
Vector3 rot = transform.localRotation.eulerAngles;
rotX = rot.x;
rotY = rot.y;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X");
float mouseY = -Input.GetAxis("Mouse Y");
rotX += mouseY * sensitivity * Time.deltaTime;
rotY += mouseX * sensitivity * Time.deltaTime;
rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);
Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
transform.localRotation = localRotation;
}
}
I tried making a different movement code and I was expecting it to let me use wasd to move in a unity puzzle game.
The thing is
transform.Translate(new Vector3(horizontalInput, 0, verticalInput) * Time.deltaTime * speed);
uses local space and since your object is rotated and looking up it will start to move upwards as well.
You could eliminate that by using global space and erase any movement on Y by doing e.g.
var move = transform.rotation * new Vector3(horizontalInput, 0, verticalInput) * Time.deltaTime * speed;
move.y = 0f;
transform.position += move;

My camera move script moves backwards on the y axis

My camera move script moves backwards on the y axis.
Here I leave the script
public class PlayerCam : MonoBehaviour
{
public float sensX;
public float sensY;
public Transform orientation;
float xRotation;
float yRotation;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
//Get mouse input
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation += mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
//rotate cam and orientation
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
}
I havent tried anything yet
I would really appreciate it if you could help me solve this problem, it can be simple and I'm sorry, I'm new to programming
If by
moves backwards on the y axis
You mean that your camera moves up when your mouses goes down and vice versa.
Then why not just multiply the mouseY variable by -1 ?
Something like this:
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY * -1;
If your problem is something different, then give more details please.

How to jump properly using character controller?

I'm using a character controller for my player movement. I had walking and running working, but I couldn't get the jumping to work.
Here is my code:
[SerializeField] Transform playerCamera = null;
[SerializeField] float mouseSensitivity = 3.5f;
[SerializeField] float walkSpeed = 10.0f;
[SerializeField] float RunSpeed = 12.0f;
[SerializeField] float gravity = 9.81f;
[SerializeField] bool lockCursor = true;
[SerializeField] [Range(0.0f, 0.5f)] float moveSmoothTime = 0.3f;
[SerializeField] [Range(0.0f, 0.5f)] float mouseSmoothTime = 0.03f;
public float jumpHeight = 3f;
Vector3 velocity;
public float verticalVelocity;
float cameraPitch = 0.0f;
float VelocityY = 0.0f;
CharacterController controller = null;
Vector2 currentDir = Vector2.zero;
Vector2 currentDirVelocity = Vector2.zero;
Vector2 currentMouseDelta = Vector2.zero;
Vector2 currentMouseDeltaVelocity = Vector2.zero;
void Start()
{
controller = GetComponent<CharacterController>();
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
void Update()
{
UpdateMouseLook();
UpdateMovement();
}
void UpdateMouseLook()
{
Vector2 targetMouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
currentMouseDelta = Vector2.SmoothDamp(currentMouseDelta, targetMouseDelta, ref currentMouseDeltaVelocity, mouseSmoothTime);
cameraPitch -= currentMouseDelta.y * mouseSensitivity;
cameraPitch = Mathf.Clamp(cameraPitch, -90.0f, 90.0f);
playerCamera.localEulerAngles = Vector3.right * cameraPitch;
transform.Rotate(Vector3.up * currentMouseDelta.x * mouseSensitivity);
}
void UpdateMovement()
{
Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
targetDir.Normalize();
currentDir = Vector2.SmoothDamp(currentDir, targetDir, ref currentDirVelocity, moveSmoothTime);
if (controller.isGrounded)
VelocityY = 0.0f;
VelocityY += gravity * Time.deltaTime;
velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * walkSpeed + Vector3.up * VelocityY;
controller.Move(velocity * Time.deltaTime);
if ((Input.GetKey("left shift") || Input.GetKey("right shift")) && controller.isGrounded && !Input.GetKey(KeyCode.S) && !Input.GetKey(KeyCode.DownArrow))
{
velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * RunSpeed + Vector3.up * VelocityY;
controller.Move(velocity * Time.deltaTime);
}
if (Input.GetKeyDown(KeyCode.J) && controller.isGrounded)
{
Debug.Log("Now Jumping!!");
VelocityY = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
Note: I'm not using rigidbody on my character.
The jumping is not working every time, on some clicks, it jumps and on most of the clicks nothing happens even Debug.Log("Now Jumping!!"); is not getting printed every time I hit J. How can I fix this?
I solved this problem. You have no choice but to add physics to the character controller. This is a simple code that has the same feature, but you should coordinate the movement and jump.
public class Player : MonoBehaviour
{
private Vector3 playerVelocity;
private CharacterController _controller;
public float jumpPower = 1f; // 1 is ok for -9.8 gravity
void Start()
{
_controller = GetComponent<CharacterController>();
}
void Update()
{
playerVelocity += Physics.gravity * Time.deltaTime;
_controller.Move(playerVelocity);
if (_controller.isGrounded)
{
playerVelocity.y = Input.GetKeyDown(KeyCode.Space) ? jumpPower : 0;
}
}
}

Mouse movement x-axis locked

I'm having a problem moving my character’s mouse in particular on x-axi.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movimentoRato : MonoBehaviour
{
public float sensibilidade = 100f;
public Transform playerBody;
float xRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * sensibilidade * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * sensibilidade * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
Mouse x-axis is locked can somebody help me?
float mouseX = Input.GetAxis("Mouse X") * 2.75f;
float mouseY = Input.GetAxis("Mouse Y") * 2.75f;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);

The player will not move where the camera is facing

when I hold down the 'w' and move the camera the player will not move in the camera direction e.g if I go forward and move the camera to the left it would not go to the left but keep going forward, What are some possible ways to fix this. Player Movement Script
public float movementspeed = 5.0F;
// Use this for initialization
void Start () {
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update () {
float translation = Input.GetAxis("Vertical") * movementspeed;
float straffe = Input.GetAxis("Horizontal") * movementspeed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translation);
}
}
and Camera View Script
public float xMoveThreshold = 1000.0f;
public float yMoveThreshold = 1000.0f;
public float yMaxLimit = 50.0f;
public float yMinLimit = -50.0f;
float yRotCounter = 0.0f;
float xRotCounter = 0.0f;
Transform player;
void Start()
{
player = Camera.main.transform;
}
// Update is called once per frame
void Update()
{
xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime;
yRotCounter += Input.GetAxis("Mouse Y") * yMoveThreshold * Time.deltaTime;
yRotCounter = Mathf.Clamp(yRotCounter, yMinLimit, yMaxLimit);
//xRotCounter = xRotCounter % 360;//Optional
player.localEulerAngles = new Vector3(-yRotCounter, xRotCounter, 0);
}
}
You need to use de camera transform to be able to do this. Something like:
public float movementspeed = 5.0F;
public Transform cameraTransform;
// Use this for initialization
void Start () {
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update () {
float translation = Input.GetAxis("Vertical") * movementspeed;
float straffe = Input.GetAxis("Horizontal") * movementspeed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
Vector3 movement = cameraTransform.Forward * translation + cameraTransform.Right * straffe;
transform.position = transform.position+ movement;
}

Categories