'How do I make Rigidbody movements in a first person shooter in Unity?
So I am making an FPS game in Unity, and I used to use transform.translate for movement, but that allows the player to move through walls if moving fast enough (diagonal movement) and it doesn't even matter how large the wall's hitbox is.
Here's my Player Controller code:
Here's the movement code:
void FixedUpdate()
{
myBody.MovePosition(transform.position + (transform.forward *
Time.deltaTime * speed));
}
void Update()
{
float axisX = Input.GetAxis ("Horizontal");
float axisY = Input.GetAxis ("Vertical");
More info: With this code, the player now moves in very specific directions, regardless of rotation. Also, W and S moves up and down rather than forwards & backwards.
Solution 1:[1]
I suggest you to checkout https://learn.unity.com/tutorial/environment-and-player?projectId=5c51479fedbc2a001fd5bb9f#5c7f8529edbc2a002053b786 unity official documentation
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
private Rigidbody rb;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
}
They have a pretty straight forward sample code on how to do it, bear in mind that this solution still needs to normalize the vectorial movement, and for that, do this:
rb.AddForce (movement.normalized * speed);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sean Gonzalez |
