Twin Stick Controller and KBM not responding (Unity C#) - c#

The problem is that when I import the code to the character it does not add the Player Input automatically and also it doesnt move at all when I press neither the controller nor the keyboard, Ive checked the code so many times but ill paste it here, it doesnt work if I add the player input manually either :(
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(PlayerInput))]
public class TwinStickMovement : MonoBehaviour
{
[SerializeField] private float playerSpeed = 5f;
[SerializeField] private float gravityValue = -9.81f;
[SerializeField] private float controllerDeadzone = 0.1f;
[SerializeField] private float gamepadRotateSmoothing = 1000f;
[SerializeField] private bool isGamepad;
private CharacterController controller;
private Vector2 movement;
private Vector2 aim;
private Vector3 playerVelocity;
private PlayerControls playerControls;
private PlayerInput playerInput;
private void Awake()
{
controller = GetComponent<CharacterController>();
playerControls = new PlayerControls();
playerInput = GetComponent<PlayerInput>();
}
private void OnEnable()
{
playerControls.Enable();
}
private void OnDisable()
{
playerControls.Disable();
}
void Update()
{
HandleInput();
HandleMovement();
HandleRotation();
}
void HandleInput()
{
movement = playerControls.Controls.Movement.ReadValue<Vector2>();
aim = playerControls.Controls.Aim.ReadValue<Vector2>();
}
void HandleMovement()
{
Vector3 move = new Vector3(movement.x, 0, movement.y);
controller.Move(move * Time.deltaTime * playerSpeed);
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
void HandleRotation()
{
}
}```

Related

How to use events in Unity?

I've watched bunch of videos about events in unity, but still cant figure out how to use them.
I have 2 scripts, in first i detect collision, second script should teleport an object with the first script attached.
First script
using UnityEngine;
public class PlayerShip : MonoBehaviour
{
private Rigidbody2D rb;
private float angle;
public delegate void TeleportHandler(GameObject Border);
public event TeleportHandler OnShipCollidedEvent;
[SerializeField] private float speedMoving;
[SerializeField] private float speedRotating;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetAxis("Horizontal") != 0)
{
angle = -Input.GetAxis("Horizontal") * Time.deltaTime * speedRotating;
transform.Rotate(transform.rotation.x, transform.rotation.y, angle);
}
if (Input.GetKey(KeyCode.W))
rb.AddRelativeForce(Vector2.up * speedMoving);
}
private void OnTriggerEnter2D(Collider2D other)
{
this.OnShipCollidedEvent?.Invoke(other.gameObject);
}
}
Second script - OnShipCollided doesn't output Test
using UnityEngine;
public class BordersCommands : MonoBehaviour
{
private PlayerShip _playerShip;
[SerializeField] private GameObject LeftBorder;
[SerializeField] private GameObject RightBorder;
[SerializeField] private GameObject BotBorder;
[SerializeField] private GameObject TopBorder;
public BordersCommands(PlayerShip _playerShip)
{
this._playerShip = _playerShip;
this._playerShip.OnShipCollidedEvent += OnShipCollided;
}
private void OnShipCollided(GameObject border)
{
Debug.Log("Test");//Here will be teleportation
}
}
Solved by adding Borders = new BordersCommands(this); in first script Start

<RigidBody> Controller

I am working on a rigidbody controller and as of right now it has some issues I cant solve. I would like my movement to be continous and if though i am checking if the player is grounded it is still jumping while in the air. Thanks in advance for any feedback its greatly appreciated!
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
private Rigidbody _playerRB;
private PlayerInputSystem _playerInput;
private float playerIdNumber;
private string uniquePlayName;
private float jumpForce = 10.0f;
[Header("IsGounded")]
public LayerMask whatIsGround;
public Transform groundCheck;
private float groundCheckRadius = 0.1f;
private float speed = 10.0f;
private float acceleration = 1.0f;
private float currentSpeed;
private void Awake()
{
_playerRB = GetComponent<Rigidbody>();
_playerInput = new PlayerInputSystem();
_playerInput.Player.Enable();
}
private void OnEnable()
{
_playerInput.Player.Jump.performed += Jump;
_playerInput.Player.Move.performed += Move;
}
private void OnDisable()
{
_playerInput.Player.Jump.performed -= Jump;
_playerInput.Player.Move.performed -= Move;
}
private void Jump(InputAction.CallbackContext obj)
{
if (Physics.CheckSphere(groundCheck.position, groundCheckRadius, whatIsGround))
{
_playerRB.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
private void Move(InputAction.CallbackContext obj)
{
float horizontal = obj.ReadValue<Vector2>().x;
float vertical = obj.ReadValue<Vector2>().y;
transform.rotation *= Quaternion.Euler(new Vector3(0, horizontal, 0));
currentSpeed += vertical * acceleration * Time.deltaTime;
currentSpeed = Mathf.Clamp(currentSpeed, 0, speed);
transform.position += transform.right * currentSpeed * Time.deltaTime;
}
}
Again thanks in advance for the help.

After adding gravity I can't run and walk faster

I'm trying to make move script but it seems impossible to me because I stared at code for like an hour I even rewrote it but same problem. It appears that after I added gravity and groundcheck things, my character cant run or even walk at set speed (he is moving very slow). Can someone please help me with it please cuz' I'm lost
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;
private Vector3 moveDirection;
private Vector3 velocity;
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity;
//REFERENCES
private CharacterController controller;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
Move();
}
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.GetKey(KeyCode.LeftShift))
{
Walk();
}
else if(moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
Run();
}
else if(moveDirection == Vector3.zero)
{
Idle();
}
moveDirection *= moveSpeed;
}
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;
}
}
I found the problem. Problem was with spawn area or call it how you want. If you'll move further the problem is no longer there.
Look at this video here: https://youtu.be/xfxgwmuPQsA

How to make FPS crawl?

I'm using Unity New Input System for my FPS game and I have figured out the movement and the mouselook. However, I'm trying to add a crawling feature to my moving script. I don't want the player to be holding down a button for crawling, it would be better to click a button to change the status from walking to crawling and then just move accordingly. and of course, the mouselook will differ in every state. How would I achieve that with the minimal code changes?
Movement class:
public class Movement : MonoBehaviour
{
[SerializeField] CharacterController controller;
[SerializeField] float walkSpeed = 10f;
[SerializeField] float runSpeed = 35f;
float moveSpeed;
Vector2 horizontalInput;
[SerializeField] float jumpHeight = 3.5f;
bool jump, running;
[SerializeField] float gravity = -30f; //-9.81
Vector3 verticalVelocity = Vector3.zero;
[SerializeField] LayerMask groundMask;
bool isGrounded;
Vector3 horizontalVelocity;
private void Update()
{
isGrounded = Physics.CheckSphere(transform.position, 0.1f, groundMask);
if (isGrounded)
{
verticalVelocity.y = 0;
}
// Jump: v = sqrt(-2 * jumpheight* gravity)
if (jump)
{
if (isGrounded)
{
verticalVelocity.y = Mathf.Sqrt(-2f * jumpHeight * gravity);
}
jump = false;
}
verticalVelocity.y += gravity * Time.deltaTime;
controller.Move(verticalVelocity * Time.deltaTime);
if (running)
{
moveSpeed = runSpeed;
horizontalVelocity = (transform.right * horizontalInput.x + transform.forward * horizontalInput.y) * moveSpeed;
controller.Move(horizontalVelocity * Time.deltaTime);
}
else
{
moveSpeed = walkSpeed;
horizontalVelocity = (transform.right * horizontalInput.x + transform.forward * horizontalInput.y) * moveSpeed;
controller.Move(horizontalVelocity * Time.deltaTime);
}
}
public void ReceiveInput(Vector2 _horizontalInput)
{
horizontalInput = _horizontalInput;
}
public void OnJumpPressed()
{
jump = true;
}
public void OnRunningPressed() {
running = true;
}
}
MouseLook class:
public class MouseLook : MonoBehaviour
{
[SerializeField] float sensitivityX = 8f;
[SerializeField] float sensitivityY = 0.5f;
float mouseX, mouseY;
[SerializeField] Transform playerCamera;
[SerializeField] float xClamp = 75f;
float xRotataion = 0f;
private void Update()
{
transform.Rotate(Vector3.up, mouseX * Time.fixedDeltaTime);
xRotataion -= mouseY;
xRotataion = Mathf.Clamp(xRotataion, -xClamp, xClamp);
Vector3 targetRotation = transform.eulerAngles;
targetRotation.x = xRotataion;
playerCamera.eulerAngles = targetRotation;
}
public void ReceiveInput(Vector2 mouseInput)
{
mouseX = mouseInput.x * sensitivityX;
mouseY = mouseInput.y * sensitivityY;
}
}
InputManager class:
public class InputManager : MonoBehaviour
{
[SerializeField] Movement movement;
[SerializeField] PlayerInteractions playerInteractions;
[SerializeField] MouseLook mouseLook;
PlayerControls controls;
PlayerControls.GroundMovementActions groundMovement;
Vector2 horizontalInput;
Vector2 mouseInput;
private void Awake()
{
controls = new PlayerControls();
groundMovement = controls.GroundMovement;
// groundMovement.[action].performed += context => do something
groundMovement.HorizontalMovement.performed += ctx => horizontalInput = ctx.ReadValue<Vector2>();
groundMovement.Jump.performed += _ => movement.OnJumpPressed();
groundMovement.Running.performed += _ => movement.OnRunningPressed();
groundMovement.PickingUp.performed += _ => playerInteractions.OnPickingUp();
groundMovement.MouseX.performed += ctx => mouseInput.x = ctx.ReadValue<float>();
groundMovement.MouseY.performed += ctx => mouseInput.y = ctx.ReadValue<float>();
groundMovement.Open.performed += _ => playerInteractions.OnOpenPressed();
}
private void Update()
{
movement.ReceiveInput(horizontalInput);
mouseLook.ReceiveInput(mouseInput);
}
private void OnEnable()
{
controls.Enable();
}
private void OnDestroy()
{
controls.Disable();
}
}
I failed to find anything like this online and I don't know how to achieve it using the new input system but here is my attempt:
public class crawlScript : MonoBehaviour
{
CapsuleCollider playerCol;
float originalHeight;
public float reducedHeight;
bool crawl = false;
void Start()
{
playerCol= GetComponent<CapsuleCollider>();
originalHeight= playerCol.height;
}
// Update is called once per frame
void Update()
{
if (crawl)
{
OnCrouch();
}
else if (!crawl)
{
GoUp();
}
}
public void OnCrouch()
{
playerCol.height= reducedHeight;
}
void GoUp()
{
playerCol.height = originalHeight;
}
public void OnCrawl()
{
crawl= true;
}
And added this to the InputManager class:
groundMovement.Crawl.performed += _ => crawlscript.OnCrawl();
You will need to
Create a public boolean variable for whether the player is crawling or not, because this will almost certainly be needed in the future by this script or other scripts.
Create a crawling animation
Create two functions for enabling and disabling crawl, that will toggle the animation, change the players walk speed, and do other things that you may want to add (like toggle the visibility of any objects in the player's hands until they get back up).
The code should look something like this:
public String crawlkey = "left shift";
public bool iscrawling = false;
// put in Update()
if(!crawling){
if(Input.GetKeyDown(crawlkey)){
iscrawling = true;
handleCrawlStart();
}
} else if(Input.GetKeyDown(crawlkey)){
iscrawling = false;
handleCrawlEnd;
}

I can't make my player move forward and backward! What is the problem?

I have been trying to create a video game but I stuck in this tutorial, in the tutorial it shows us to use input actions addon (What that does is it makes W-A-S-D or joystick type of keys easy to use) but even I watched the video after 3rd time I couldn't find the mistake! the problem is that I am not able to move my player forward or backward, I can only move it right and left. Please help I have tried so many things, like restarting the program or changing some code but it's not working can you help me to fix it?
Here is the first code to take the WASD commands from the addon script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputManager : MonoBehaviour
{
//Takes the wasd controls from addon
InputWASD playerControls;
public Vector2 movementInput;
public float verticalInput;
public float horizontalInput;
private void OnEnable()
{
if (playerControls == null)
{
playerControls = new InputWASD();
playerControls.PlayerMovement.Movement.performed += i => movementInput = i.ReadValue<Vector2>();
}
playerControls.Enable();
}
private void OnDisable()
{
playerControls.Disable();
}
public void HandleAllInputs()
{
HandleMovementInput();
//TODO: HandleJumpInput
// HandleAttackInput
// HandleDashInput
// HandleAbilityInput
}
private void HandleMovementInput()
{
verticalInput = movementInput.y;
horizontalInput = movementInput.x;
}
}
Here is the second code to use keys in movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAct : MonoBehaviour
{
InputManager inputManager;
Vector3 moveDirection;
Transform cameraObject;
Rigidbody playersRB;
public float moveSpeed = 6f;
public float rotationSpeed = 15f;
private void Awake()
{
inputManager = GetComponent<InputManager>();
playersRB = GetComponent<Rigidbody>();
cameraObject = Camera.main.transform;
}
public void HandleAllAction()
{
HandleMovement();
HandleRotation();
}
private void HandleMovement()
{
moveDirection = cameraObject.forward * inputManager.verticalInput;
moveDirection = moveDirection + cameraObject.right * inputManager.horizontalInput;
moveDirection.Normalize();
moveDirection.y = 0;
moveDirection = moveDirection * moveSpeed;
Vector2 movementVelocity = moveDirection;
playersRB.velocity = movementVelocity;
}
private void HandleRotation()
{
Vector3 targetDirection = Vector3.zero;
targetDirection = cameraObject.forward * inputManager.verticalInput;
targetDirection = targetDirection + cameraObject.right * inputManager.horizontalInput;
targetDirection.Normalize();
targetDirection.y = 0;
if (targetDirection == Vector3.zero)
{
targetDirection = transform.forward;
}
Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
Quaternion playerRotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
transform.rotation = playerRotation;
}
}
Here is the third and last code to use first 2 codes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMain : MonoBehaviour
{
//Calling scripts
InputManager inputManager;
PlayerAct playerAct;
private void Awake()
{
inputManager = GetComponent<InputManager>();
playerAct = GetComponent<PlayerAct>();
}
private void Update()
{
inputManager.HandleAllInputs();
}
private void FixedUpdate()
{
playerAct.HandleAllAction();
}
}
I did what the man told me (in the tutorial) but mine is not working!
sometime maybe the video is so old and unity is keep updating so some code maybe is not work anymore , maybe you should use the getinput system like float x= Input.GetAxis("Horizontal")); and float z = Input.GetAxis("Vertical"); this two is use characterController and let see how it work

Categories

Resources