Movement based on camera (235318)

I have the following code that moves the character, however it moves based on world instead of camera facing. I’m using Cinemachine to rotate the camera throughout the game, so how can I change this to get the character to move in relation to camera?

void Move()
    {
        float xInput = Input.GetAxis("Horizontal");
        float zInput = Input.GetAxis("Vertical");

        Vector3 dir = new Vector3(xInput, 0, zInput) * moveSpeed;
        dir.y = rig.velocity.y;

        rig.velocity = dir;

        Vector3 facingDir = new Vector3(xInput, 0, zInput);

        if (facingDir.magnitude > 0)
        {
            transform.forward = facingDir;
        }
    }

Did you figure this out? I am tackling this issue as well at the moment. I have a rb that is being moved with addforce. I want to move the ball toward where the camera is pointing.

2 Answers

2

Did you figure this out? I am tackling this issue as well at the moment. I have a rb that is being moved with addforce. I want to move the ball toward where the camera is pointing.

Yes, this is usually one of my favourite solutions, but keep in mind in order for this to work your "init" method has to return it's own instance. So you need a return this; at the end. (btw: your init method should be PascalCase and start with a capital letter).

if you want to move in local space:

Vector3 dir = new Vector3(xInput * tr.right, rig.velocity.y, zInput * tr.forward) * moveSpeed //transform could be the transform of you camera

What do you mean? This would be valid "C# 1" code. (if Unity already existed at that time ^^).Though the generic version is actually the more compact way and less error prone. Using "typeof" and a cast you have to use the type twice. So it's a potential problem when during manual refactoring you might change the type but forgot the other. The generic CreateInstance<T> doesn't require a seperate cast.