How do I add running and animations to my player controller script? - c#

I am new to Unity and have been having a hard time adding running and animations (I have the animations and they are set up in animator) to my FPS controller script. Can someone please help me add running and animations? I would be extremely grateful.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
Animator anim;
float RotateX;
float RotateY;
public static bool GamePaused;
[SerializeField]
[Header("Game Objects")]
public GameObject Camera;
public GameObject PauseMenu;
public GameObject Player;
[Header("Movement Settings")]
public float WalkSpeed = 5.0f;
public float RunSpeed = 10.0f;
[Header("Rotation Settings")]
public float RorationSpeed;
public float MaxYAxis = 60.0f; // right
public float MinYAxis = -48.0f; // left
public bool Grounded;
private void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * WalkSpeed * Time.deltaTime);
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * WalkSpeed * Time.deltaTime);
RotateX += Input.GetAxis("Mouse X") * RorationSpeed;
RotateY += Input.GetAxis("Mouse Y") * RorationSpeed;
RotateY = Mathf.Clamp(RotateY, MinYAxis, MaxYAxis);
Camera.transform.localRotation = Quaternion.Euler(-RotateY, 0f, 0f);
transform.rotation = Quaternion.Euler(0f, RotateX, 0f);
}
}
Here is what I have to trigger the different animations in the animator, but the animation follows through when I release the key rather than switching immediately upon release.
if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.A) ||
Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.D) ||
Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.LeftArrow) ||
Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.RightArrow))
{
anim.SetBool("IsWalking", true);
}
if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyDown(KeyCode.A) ||
Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.D) ||
Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.LeftArrow) ||
Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.RightArrow))
{
anim.SetBool("IsWalking", false);
}

What I can suggest is that you use the horizontal and vertical axes, rather than hard-coded key presses.
More specifically, first of all (if you have not already) in the animator window create an idle state and a walking animation state. You will need somehow to transition between the two states. To do that you will need to create a new bool parameter (let's name it "isWalking" as you did) and create a new condition between the idle and the walking state. For example, set to transition between "idle" to "walking" when isWalking is true and transition between "walking" to "idle" when isWalking is false.
Now in your PlayerController script in the update or fixed update you can add the following code
horizontalMovement = Input.GetAxis("Horizontal");
verticalMovement = Input.GetAxis("Vertical");
//normalize vector so movement in two axis simultanesly is balanced.
moveDirection = (horizontalMovement * transform.right + verticalMovement * transform.forward).normalized;
/* based on your code although a rigid body solution or character controller would have been more robust */
transform.Translate(moveDirection * WalkSpeed * Time.deltaTime);
if (horizontal != 0 || vertical != 0)
{
animator.setFloat("isWalking",true);
}
else
{
animator.setFloat("isWalking",false);
}
However this solution is working is implemented based on the code you provided. If you want to switch in a more robust and easy to maintain script you can use this free controller that uses a rigidbody and has animations already installed and working.
https://github.com/PanMig/First-Person-Unity-Camera

Here is my working script with walking, running, jumping and animation triggers.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
Animator anim;
float RotateX;
float RotateY;
Rigidbody rb;
public static bool GamePaused;
public bool isGrounded;
[SerializeField]
[Header("Game Objects")]
public GameObject Camera;
public GameObject PauseMenu;
public GameObject Player;
[Header("Movement Settings")]
public float DefaultSpeed = 5.0f;
public float WalkSpeed = 5.0f;
public float RunSpeed = 10.0f;
public float jumpForce = 2.5f;
public Vector3 jump;
[Header("Rotation Settings")]
public float RorationSpeed = 3.0f;
public float MaxYAxis = 60.0f;
public float MinYAxis = -48.0f;
private void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 1.0f, 0.0f);
}
void Update()
{
Rotation();
Movement();
Bool();
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
void Rotation()
{
RotateX += Input.GetAxis("Mouse X") * RorationSpeed;
RotateY += Input.GetAxis("Mouse Y") * RorationSpeed;
RotateY = Mathf.Clamp(RotateY, MinYAxis, MaxYAxis);
Camera.transform.localRotation = Quaternion.Euler(-RotateY, 0f, 0f);
transform.rotation = Quaternion.Euler(0f, RotateX, 0f);
}
void Movement()
{
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * WalkSpeed * Time.deltaTime);
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * WalkSpeed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.LeftShift))
{
WalkSpeed = RunSpeed;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
WalkSpeed = DefaultSpeed;
}
}
void Bool()
{
if (Input.GetKeyDown(KeyCode.W))
{
anim.SetBool("IsWalkingForward", true);
}
if (Input.GetKeyDown(KeyCode.A))
{
anim.SetBool("IsWalkingLeft", true);
}
if (Input.GetKeyDown(KeyCode.S))
{
anim.SetBool("IsWalkingBack", true);
}
if (Input.GetKeyDown(KeyCode.D))
{
anim.SetBool("IsWalkingRight", true);
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
anim.SetBool("IsWalkingForward", true);
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
anim.SetBool("IsWalkingLeft", true);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
anim.SetBool("IsWalkingBack", true);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
anim.SetBool("IsWalkingRight", true);
}
if (Input.GetKeyUp(KeyCode.W))
{
anim.SetBool("IsWalkingForward", false);
}
if (Input.GetKeyUp(KeyCode.A))
{
anim.SetBool("IsWalkingLeft", false);
}
if (Input.GetKeyUp(KeyCode.S))
{
anim.SetBool("IsWalkingBack", false);
}
if (Input.GetKeyUp(KeyCode.D))
{
anim.SetBool("IsWalkingRight", false);
}
if (Input.GetKeyUp(KeyCode.UpArrow))
{
anim.SetBool("IsWalkingForward", false);
}
if (Input.GetKeyUp(KeyCode.LeftArrow))
{
anim.SetBool("IsWalkingLeft", false);
}
if (Input.GetKeyUp(KeyCode.DownArrow))
{
anim.SetBool("IsWalkingBack", false);
}
if (Input.GetKeyUp(KeyCode.RightArrow))
{
anim.SetBool("IsWalkingRight", false);
}
}
void OnCollisionStay()
{
isGrounded = true;
}
void OnCollisionExit()
{
isGrounded = false;
}
}

Related

multiplayer health system in unity using photon (beginner)

I am using photon to make a multiplayer fps game in unity and have a player script for the health and other items. For some reason, when i run this outside of the editor (in a real build) none of the bullets do damage or the damage does not register, but when I go into unity and use the built in play function, my bullets do damage to each player. is there any way that I can have all 3 of the damage systems working? Most of the code below is for the first person, the only code that really matters is the OnCollisionEnter function.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using TMPro;
public class camerainput : MonoBehaviourPunCallbacks
{
public GameObject Camera;
float xRotation = 0f;
public Vector2 turn;
public float sensitivity = 50;
public Vector3 deltaMove;
public float speed = 1;
public float movespeed = 0.5f;
public float health = 5;
public TextMeshProUGUI text;
public GameObject bullet;
public GameObject barrel;
public float firerate = 1;
public float delay = 0f;
public bool IsControlling = true;
// Start is called before the first frame update
void Start()
{
if (photonView.IsMine)
{
Camera.SetActive(true);
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
void HitMarker()
{
if (!photonView.IsMine)
{
Camera.SetActive(false);
}
}
public void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "bullet")
{
health -= 1;
Debug.Log("hit");
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
IsControlling = false;
}
if (photonView.IsMine)
{
text.SetText(health.ToString());
if (health == 0)
{
transform.position += transform.forward * Time.deltaTime * 500;
}
if (IsControlling == true)
{
turn.x += Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
turn.y = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
xRotation -= turn.y;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, turn.x, 0);
}
text.SetText(health.ToString());
if (Input.GetKey(KeyCode.W))
{
transform.position += transform.forward * Time.deltaTime * movespeed;
}
if (Input.GetKey(KeyCode.S))
{
transform.position -= transform.forward * Time.deltaTime * movespeed;
}
if (Input.GetKey(KeyCode.D))
{
transform.position += transform.right * Time.deltaTime * movespeed;
}
if (Input.GetKey(KeyCode.A))
{
transform.position -= transform.right * Time.deltaTime * movespeed;
}
if (Input.GetMouseButton(0) && Time.time > delay)
{
delay = Time.time + 1f/firerate;
Instantiate(bullet, barrel.transform.position, Camera.transform.rotation);
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
IsControlling = true;
}
}
}
}

My primary character controls the newly joined session character

This is my movement script.
public class PlayerMovement : MonoBehaviour
{
// VARIABLES
public float movementSpeed;
public float walkSpeed;
public float runSpeed;
private Vector3 moveDirection;
private Vector3 velocity;
public bool isGrounded;
public float groundCheckDistance;
public LayerMask groundMask;
public float gravity;
// References
public CharacterController controller;
public Animator anim;
PhotonView view;
private void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponentInChildren<Animator>();
view = GetComponent<PhotonView>();
}
private void Update()
{
if (view.IsMine)
{
Move();
}
}
private void Move()
{
if (view.IsMine)
{
isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float moveZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, moveZ);
moveDirection = transform.TransformDirection(moveDirection);
if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift))
{
// WALK
Walk();
}
else if(moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
// RUN
Run();
}
else if(moveDirection == Vector3.zero)
{
// IDLE
Idle();
}
moveDirection *= movementSpeed;
controller.Move(moveDirection * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
private void Idle() {
if (view.IsMine)
{
anim.SetFloat("Speed", 0, 0.1f, Time.deltaTime);
}
}
private void Walk()
{
if (view.IsMine)
{
movementSpeed = walkSpeed;
anim.SetFloat("Speed", 0.5f, 0.1f, Time.deltaTime);
}
}
private void Run(){
if (view.IsMine)
{
movementSpeed = runSpeed;
anim.SetFloat("Speed", 1, 0.1f, Time.deltaTime);
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class SpawnPlayers : MonoBehaviour
{
public GameObject playerPrefab;
public float minX;
public float maxX;
public float minZ;
public float maxZ;
public float minY;
public float maxY;
// Start is called before the first frame update
private void Start()
{
Vector3 randomPosition = new Vector3(Random.Range(minX, maxX), Random.Range(minY, maxY), Random.Range(minZ, maxZ));
player = PhotonNetwork.Instantiate(playerPrefab.name, randomPosition, Quaternion.identity);
}
}
The code above is the join session code
I also have a really basic camera function that just allows the character to look but I don't think anything is wrong with that. The view.IsMine at least makes it so that the users can not control both characters at the same time but it still allows for other person controller and can't control his own character. Is there anyone that knows how to fix this issue?

Flickering IsGrounded function

IsGrounded Function started flickering when I added OBJs to my project. It was working perfectly before I started working on it today it only started after I added some material and OBJS. I tried reverting to the state it was in before I added different elements but the problem still happened. It always occurs after about 30 seconds of running the game in the window. How can I fix this?
\using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
//VARIABLES
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
public float _speed = 10;
public float _rotationSpeed = 180;
private Vector3 moveDirection;
private Vector3 Velocity;
private Vector3 rotation;
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity;
[SerializeField] private float jumpHeight;
//REFERNCES
private CharacterController controller;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
Move();
this.rotation = new Vector3(0, Input.GetAxisRaw("Horizontal") * _rotationSpeed * Time.deltaTime, 0);
Vector3 move = new Vector3(0, 0, Input.GetAxisRaw("Vertical") * Time.deltaTime);
move = this.transform.TransformDirection(move);
controller.Move(move * _speed);
this.transform.Rotate(this.rotation);
}
private void Move()
{
isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);
if (isGrounded && Velocity.y < 0)
{
Velocity.y = -2f;
}
float moveZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, moveZ);
if (isGrounded)
{
if (moveDirection != Vector3.zero && !Input.GetButtonDown("Fire3"))
{
Walk();
}
else if (moveDirection != Vector3.zero && Input.GetButtonDown("Fire3"))
{
Run();
}
else if (moveDirection == Vector3.zero)
{
Idle();
}
moveDirection *= moveSpeed;
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}
controller.Move(moveDirection * Time.deltaTime);
Velocity.y += gravity * Time.deltaTime;
controller.Move(Velocity * Time.deltaTime);
}
private void Idle()
{
}
private void Walk()
{
moveSpeed = walkSpeed;
}
private void Run()
{
moveSpeed = runSpeed;
}
private void Jump()
{
Velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
}

Xbox one controller spinning player in unity 3d

I am making an fps game and I want to map my Xbox one controller so that I can use it in my game. All of the buttons and the left joystick work. But, when I try to map the right joystick and play the game my camera looks up and my player starts spinning around. Here is the code for my camera: `
public string mouseXinputname, mouseYinputname;
public float mouseSensitivity;
private float Xaxisclamp;
[SerializeField] private Transform playerBody;
private void Awake()
{
LockCursor();
Xaxisclamp = 0.00f;
}
private void LockCursor ()
{
Cursor.lockState = CursorLockMode.Locked;
}
private void Update()
{
CameraRotaion();
}
private void CameraRotaion ()
{
float mouseX = Input.GetAxis(mouseXinputname) * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis(mouseYinputname) * mouseSensitivity * Time.deltaTime;
transform.Rotate(Vector3.left * mouseY);
playerBody.Rotate(Vector3.up * mouseX);
Xaxisclamp += mouseY;
if(Xaxisclamp > 90.0f)
{
Xaxisclamp = 90.0f;
mouseY = 0.0f;
ClampXaxisRotationToValue(270.0f);
}
else if (Xaxisclamp < -90.0f)
{
Xaxisclamp = -90.0f;
mouseY = 0.0f;
ClampXaxisRotationToValue(90.0f);
}
}
private void ClampXaxisRotationToValue(float value)
{
Vector3 eulerRotation = transform.eulerAngles;
eulerRotation.x = value;
transform.eulerAngles = eulerRotation;
}`
And here is the code for my player controller:
public CharacterController character;
public float speed = 10f;
Vector3 velocity;
public float gravtiy = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool isGrounded;
public float jumpHeight = 3f;
public float sprint = 20f;
public float crouchHeight = 1.0f;
public float crouchSpeed = 5f;
private void Start()
{
character.GetComponent<CharacterController>();
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0 )
{
velocity.y = -2.0f;
}
if (Input.GetButtonDown("Sprint"))
{
speed = sprint;
}
if (Input.GetButtonUp("Sprint"))
{
speed = 10f;
}
if (Input.GetButtonDown("Crouch"))
{
character.height = crouchHeight;
speed = crouchSpeed;
}
if (Input.GetButtonUp("Crouch"))
{
character.height = 2f;
speed = 10f;
}
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
Vector3 move = transform.right * hor + transform.forward * ver;
character.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravtiy);
}
velocity.y += gravtiy * Time.deltaTime;
character.Move(velocity * Time.deltaTime);
I included all of my code so you can copy and paste it into your own unity project so you can see what I mean.
BTW: The inputs "Crouch" and "Sprint" are custom inputs and you'll have to create them in Project Settings > Input Manager

How can I make character to crouch and also moving faster when left shift key is holding down?

This is a screenshot of the Input settings in the editor there is no crouch and no left shift to make the player moving faster.
This is my script name character controller. attached to the FPSController(Player).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterController : MonoBehaviour
{
public float moveSpeed = 10.0f;
public float jumpForce = 2.0f;
void Start()
{
}
// Update is called once per frame
void Update ()
{
float translatioin = Input.GetAxis("Vertical") * moveSpeed;
float straffe = Input.GetAxis("Horizontal") * moveSpeed;
translatioin *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translatioin);
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
transform.Translate(0, jumpForce * Input.GetAxis("Jump") * Time.deltaTime, 0);
}
}
I want to add crouch and left shift for faster moving.
This script is only for controlling the mouse looking around and lock state of the mouse cursor attached to the main camera(Player child).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camMouseLook : MonoBehaviour
{
Vector2 mouseLook;
Vector2 smoothV;
public float sensitivity = 5.0f;
public float smoothing = 2.0f;
public bool mouseDown = false;
public bool cursorLock = false;
public HandleMouseCursor handleMouseCursor;
GameObject character;
// Use this for initialization
void Start ()
{
if(cursorLock == false)
{
Cursor.lockState = CursorLockMode.None;
handleMouseCursor.setMouse();
}
else
{
Cursor.lockState = CursorLockMode.Locked;
}
character = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButton(0) && mouseDown == true)
{
MouseLook();
}
else
{
if (mouseDown == false)
{
MouseLook();
}
}
}
private void MouseLook()
{
if (cursorLock == false)
{
Cursor.lockState = CursorLockMode.None;
handleMouseCursor.setMouse();
}
else
{
Cursor.lockState = CursorLockMode.Locked;
}
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
mouseLook.y = Mathf.Clamp(mouseLook.y, -90f, 90f);
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);
}
}
You can change speed of your movement in your CharacterController script.
Just create a variable for crouch speed and multiplay it to your translation vector.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterController : MonoBehaviour
{
public float moveSpeed = 10.0f;
public float crouchSpeed = 20;
public float jumpForce = 2.0f;
void Start()
{
}
// Update is called once per frame
void Update ()
{
float finalMoveSpeed = moveSpeed;
// you can add more IF statements for more actions like walking, running, jumping,...
if(Input.GetKey(KeyCode.KeyCode.LeftShift))
finalMoveSpeed = crouchSpeed ;
float translatioin = Input.GetAxis("Vertical") * finalMoveSpeed ;
float straffe = Input.GetAxis("Horizontal") * finalMoveSpeed ;
translatioin *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translatioin);
if (Input.GetKeyDown("escape"))
{
Cursor.lockState = CursorLockMode.None;
}
transform.Translate(0, jumpForce * Input.GetAxis("Jump") * Time.deltaTime, 0);
}
}

Categories