CharacterController is not moving correctly - c#

im starting a new proyect in Unity and I want my character to jump and move at the same time but the codes don't work well together. the character finds it difficult to move. both work perfectly separately
this is the code im using to move around:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 30f;
public float turnSpeed = 80f;
private float horizontalInput;
private float verticalInput;
// Update is called once per frame
void Update()
{
horizontalInput = Input.GetAxis("Horizontal"); //teclas
verticalInput = Input.GetAxis("Vertical");
transform.Translate(speed*Time.deltaTime*Vector3.forward*verticalInput); //movimiento
transform.Rotate(turnSpeed*Time.deltaTime*Vector3.up*horizontalInput); //rotar
}
}
and this one is a tutorial i found for jumping:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JumpControl : MonoBehaviour
{
private CharacterController controller;
private float verticalVelocity;
private float gravity = 14.0f;
private float jumpForce = 10.0f;
void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update(){
if (controller.isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Space))
{
verticalVelocity = jumpForce;
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
Vector3 moveVector = new Vector3(0, verticalVelocity, 0);
controller.Move(moveVector * Time.deltaTime);
}
}

The CharacterController is physics-based. You never want to mix a physics-based movement with applying transformations via the Transform component. This breaks the physics, collision detection and causes all kind of unexpected behaviour and strange looking movements.
So instead of
transform.Translate(speed*Time.deltaTime*Vector3.forward*verticalInput);
you would rather want to do
[SerializeField] private CharacterController controller;
private void Awake()
{
if(!controller) controller = GetComponent<CharacterController>();
}
void Update()
{
horizontalInput = Input.GetAxis("Horizontal"); //teclas
verticalInput = Input.GetAxis("Vertical");
transform.Rotate(turnSpeed * Time.deltaTime * Vector3.up * horizontalInput);
controller.Move(speed * Time.deltaTime * Vector3.forward * verticalInput);
}

This code
transform.Translate(speedTime.deltaTimeVector3.forward*verticalInput);
prevents the jump action.
So you can replace it with
rb.AddForce(new Vector3(horizontalInput , o, verticalInput) * speed);

Related

How do I fix my 2D player movement in Unity?

I'm new to unity and have been trying to get the 2D Playermovement right for quite some time. Yet for some reason this error keeps popping up, anyone have any ideas?
this is the code I've been using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2d rb2D;
private float MovementSpeed;
private float JumpForce;
private bool IsJumping;
private float moveHorizontal;
private float moveVertical;
// Start is called before the first frame update
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2d>();
MovementSpeed = 3f;
JumpForce = 60f;
IsJumping = false;
}
// Update is called once per frame
void Update()
{
moveHorizontal = Input.GetAxisRaw("Horizontal");
moveVertical = Input.GetAxisRaw("Vertical");
}
void FixedUpdate ()
{
if(moveHorizontal > 0.1f || moveHorizontal < -0.1f)
{
rb2D.AddForce(new Vector2(moveHorizontal * MovementSpeed, 0f), ForceMode2D.Impulse);
}
}
}
Typo: It should be Rigidbody2D and not Rigidbody2d

Unity 2d error' Transform' does not contain a definition for 'postion'

I want to create a 2d game but when I want the player to avoid being able to jump infinitely in the air by recovering his position I get an error.
My error :
Transform' does not contain a definition for 'postion' and no
accessible extension method 'postion' accepting a first argument of
type 'Transform' could be found
My code :
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public float jumpForce;
public Rigidbody2D rb;
private Vector3 velocity = Vector3.zero;
public bool isJumping;
public bool isGrounded;
public Transform groundCheckLeft;
public Transform groundCheckRight;
// Update is called once per frame
void FixedUpdate()
{
isGrounded = Physics2D.OverlapArea(groundCheckLeft.Position, groundCheckRight.Position);
float horizontalMovement = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
if (Input.GetButtonDown("Jump") && isGrounded)
{
isJumping = true;
}
MovePlayer(horizontalMovement);
}
void MovePlayer(float _horizontalMovement)
{
Vector3 targetVelocity = new Vector2(_horizontalMovement, rb.velocity.y);
rb.velocity = Vector3.SmoothDamp(rb.velocity, targetVelocity, ref velocity, .05F);
if(isJumping == true)
{
rb.AddForce(new Vector2(0f, jumpForce));
isJumping = false;
}
}
}
It's transform.position not postion
Edit: Yep, just like Snir Ego said.
the solution should be simple, you wrote groundCheckLeft.Postion instead of groundCheckLeft.position

Movement really slow in Unity

I'm working on a very basic side scrolling platformer in Unity 3D. The player is a cube, you can move left and right, you can jump. I can't get the movement correct as the character moves too slow.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float walkSpeed = 15f;
public float jumpSpeed = 15f;
public float gravity = 50f;
Rigidbody rb;
bool pressedJump = false;
Vector3 movementInput;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
movementInput = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
}
void FixedUpdate()
{
WalkHandler();
JumpHandler();
GravityHandler();
}
void WalkHandler()
{
rb.velocity = new Vector2(0f, rb.velocity.y);
rb.velocity = movementInput * walkSpeed * Time.fixedDeltaTime;
}
void JumpHandler()
{
if (Input.GetButtonDown("Jump"))
{
if (!pressedJump)
{
pressedJump = true;
Vector3 jumpVector = new Vector3(0f, jumpSpeed, 0f);
rb.velocity = rb.velocity + jumpVector;
}
}
else
{
pressedJump = false;
}
}
void GravityHandler()
{
rb.AddForce(Vector3.down * gravity * rb.mass);
}
}
More context I originally had this implemented and it worked. Very smooth movement and jumping. I tragically lost that game due to my own actions. So I'm trying to recreate it. Here is a video of the original movement and jumping I'm looking to recreate:
My Progress so Far
Note: The values for walkSpeed, jumpForce and gravity were what was used previously.
Losing the first game was pretty soul crushing so any help would be great.
OK so I'm not sure how to recreate this using velocity but this seems to work:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float walkSpeed = 15f;
public float jumpSpeed = 15f;
public float gravity = 50f;
Rigidbody rb;
bool pressedJump = false;
float hAxis;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
hAxis = Input.GetAxisRaw("Horizontal");
}
void FixedUpdate()
{
WalkHandler();
JumpHandler();
GravityHandler();
}
void WalkHandler()
{
rb.velocity = new Vector2(0f, rb.velocity.y);
Vector3 movement = new Vector2(hAxis * walkSpeed * Time.deltaTime, 0f);
rb.MovePosition(transform.position + movement);
}
void JumpHandler()
{
if (Input.GetButtonDown("Jump"))
{
if (!pressedJump)
{
pressedJump = true;
Vector3 jumpVector = new Vector3(0f, jumpSpeed, 0f);
rb.velocity = rb.velocity + jumpVector;
}
}
else
{
pressedJump = false;
}
}
// Check if the object is grounded
bool CheckGrounded()
{
return true;
}
void GravityHandler()
{
rb.AddForce(Vector3.down * gravity * rb.mass);
}
}
Ignore the CheckGrounded method

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);
}
}

Why when rotating an object with the mouse it's rotating to the opposite direction?

public class Rotate : MonoBehaviour
{
public float speed = 1.0f;
private void Update()
{
transform.Rotate(new Vector3(Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), 0) * Time.deltaTime * speed);
}
}
I want to rotate an object smooth with the mouse.
But in this case if I move the mouse to the right it's rotating the object to the left and if moving up the mouse it's rotating down.
This is working just like I wanted :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseOrbit : MonoBehaviour
{
public float speedH = 2.0f;
public float speedV = 2.0f;
private float yaw = 180.0f;
private float pitch = 0.0f;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
yaw -= speedH * Input.GetAxis("Mouse X");
pitch -= speedV * Input.GetAxis("Mouse Y");
transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
}
}

Categories