Reputation: 11
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);
}
}
Upvotes: 1
Views: 894
Reputation: 90630
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);
}
Upvotes: 2
Reputation: 141
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);
Upvotes: 0