I am having trouble with getting a movement based on rotation with physics (like going up ramps, jumping, and running into walls), I can look around with another code but I cant get the capsule to move with the direction its pointing in, and when i do, I cant jump, go up ramps, and I can walk though walls. can someone please help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pm : MonoBehaviour
{
CharacterController characterController;
public float movementSpeed;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
public float speed = 9.0f;
public Vector3 jump;
public float jumpForce = 2.0f;
public bool isGrounded;
Rigidbody rb;
private Vector3 moveDirection = Vector3.zero;
// Use this for initialization
void Start()
{
characterController = GetComponent<CharacterController>();
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 2.0f, 0.0f);
}
void OnCollisionStay()
{
isGrounded = true;
}
//Update is called once per frame
void FixedUpdate()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
Cursor.visible = false;
if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey("w"))
{
transform.position = transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed * 2.5f;
}
else if (Input.GetKey("w") && !Input.GetKey(KeyCode.LeftShift))
{
transform.position = transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed;
}
else if (Input.GetKey("s"))
{
transform.position -= transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed;
}
if (Input.GetKey("a") && !Input.GetKey("d"))
{
transform.position = transform.TransformDirection(Vector3.left) * Time.deltaTime * movementSpeed;
}
else if (Input.GetKey("d") && !Input.GetKey("a"))
{
transform.position -= transform.TransformDirection(Vector3.left) * Time.deltaTime * movementSpeed;
}
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
moveDirection *= speed;
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
}
CodePudding user response:
First of all you should not use FixedUpdate() for getting the input as it does not run every frame. you will skip input sometimes during the gameplay. Use it in Update().
And for following the camera movement. use = transform.LookAt(target.transform.position);
CodePudding user response:
The problem is you are trying to override transform.position with rb.AddForce(). transform.position is setting your (x,y,z) to some exact value every frame and you are trying to add force to your y value at the exact same time your transform.position is setting your y value to 0. Don't use transform.position = for movement system. You could use your moveDirection which you have defined but never used as transform.Translate(moveDirectionmovementSpeedTime.deltaTime);