How to move character relative to camera using AddForce

I get an error: Operator * cannot be applied to operands by type Vector3 and Vector3

_rb.AddForce(movement * Camera.main.transform.forward * speed * Time.fixedDeltaTime, ForceMode.Impulse);

Movement and Camera.main.transform.forward is two Vector3. You cannot multiple two Vector3 together. What you want to do is express the movement in the space of the camera. If I’m not mistaken, you will need to use _rb.AddForce(camera.transform.InverseTransformDirection(movement) * speed, ForceMode.Impulse).

There is 4 things that you should consider also:

  1. Whenever you add a force, you do not need to multiply it by deltaTime. Add force is like adding a velocity to an object, if you modulate it by the deltaTime, you then now add a displacement which is not what you want. (You want a displacement overtime)
  2. Camera.main could be expensive to do depending of your version of Unity. It is also better, in my opinion, to always cache object/component that won’t change during the execution.
  3. You should not use AddForce for the movement of your character. Instead, you should use RigidBody.MovePosition
  4. You should consider using the CharacterController for prototype or if you are new to Unity.

void Update () {
if(Input. GetButtonDown(“fus”)){
crate. rigidbody. AddForce(cameraRelativeRight * power);
crate. rigidbody. AddForce(cameraRelativeForward * power);
Caregiver Connect

You can’t multiply two vectors together as you do it with two floats. Vectors can be combined in various ways, like with Vector3.Scale, Vector3.Cross or Vector3.Dot.

Also, usually it’s easier to control a character with a Character Controller component. But, of course, it depends on what you’re trying to achieve in your game.

Anyways, here’s a simpler way to do it.

Vector3 cameraSpaceMovement = Camera.main.TransformDirection (movement);

_rb.AddForce (speed * Time.fixedDeltaTime * cameraSpaceMovement), ForceMode.Impulse);

Note: for good performances, it’s always better to write the vector at the end of the series of the operands to multiply, otherwise it’ll multiply each axis for each operation in between.