- Home /
Question by
L96416D18C552SCOPE · Mar 28, 2021 at 11:19 PM ·
movementrigidbodytransformcharactercontrollerthird-person
Movement with physics
I'm making Third Person player movement with physics. But there are some problems with making movement.
transform.Translate doesn't check if the object collides or not. RigidBody.MovePosition keep goes through walls if I give speed faster. Docs recommend not to modify Rigidbody.velocity directly. And CharacterController doesn't have physics. Is there any other solution for moving objects?
Comment
Answer by Zymurer · Mar 30, 2021 at 12:38 PM
Yes there is. With AddForce. But first you need to have a rigidbody3D component. Also set rigidbody drag. Otherwise your character will go forever with it's momentum. Here is a starting script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//This will attach a rigidbody component automatically. But you still need to assign it to rb.
[RequireComponent(typeof(Rigidbody))]
public class MoveWithRigidbody : MonoBehaviour {
public Rigidbody rb;
//Line 11 is optional. You can delete it or change the values. Just don't set Speed to zero.
[Range(0.1f,100)]
public float Speed;
// Update is called once per frame
void Update () {
rb = gameObject.GetComponent<Rigidbody>();
if (Input.GetKey(KeyCode.W))
{
//For movement you may use AddForce, AddRelativeForce etc.
rb.AddForce(Vector3.forward * Speed);
}
if (Input.GetKey(KeyCode.S))
{
//For movement you may use AddForce, AddRelativeForce etc.
rb.AddForce(Vector3.forward * -Speed);
//or rb.AddForce(Vector3.back * Speed);
}
if (Input.GetKey(KeyCode.A))
{
//For movement you may use AddForce, AddRelativeForce etc.
rb.AddForce(Vector3.right * -Speed);
//or rb.AddForce(Vector3.left * Speed);
}
if (Input.GetKey(KeyCode.D))
{
//For movement you may use AddForce, AddRelativeForce etc.
rb.AddForce(Vector3.right * Speed);
}
}
}
Btw, fell free to ask if there is a point you didn't understand. Hope this helps.