Let’s say I have the player’s velocity(based on the character controller) and I wanted the player to get launched into the air if they step on a mine. I could do characterController.velocity.y = mineVelocity. This works, but what if I wanted the player to get knocked back when they are shot. If I do characterController.velocity.z = knockbackVelocity the velocity.z is always the same direction not oriented to where the player is facing. How can I set the velocity to a specific direction? I know people will say use a rigidbody but there are complex reasons why I do not want to. Any advice on the matter would be greatly appreciated.
To get the pedantry out of the way… velocity always has direction. Velocity is speed in a given direction.
We usually represent this as a Vector (which has magnitude and direction, the magnitude being speed, the direction being… direction).
With that said.
What you’re describing is setting the ‘z’ or ‘y’ or whatever member of the velocity vector. And thusly that is your defined direction. You’re setting ‘z’ to some float/scalar meaning that the direction is always along the z axis.
If you want direction you need to come up with a Vector to represent that direction, and then scale it to the speed you’d like. Giving you your total velocity. You can add that to the existing velocity, set it to the existing velocity, or doing any other arithmetic to the existing velocity with the new velocity to get different results.
For example just setting it to that new velocity will hault all motion in any other direction and make the player move in explicitly that knockback direction.
Where as adding will combine the 2 together.
…
Question.
What is this ‘characterController’?
Is it a CharacterController?
If it is, that velocity property really only reports the velocity that results from the last call to ‘Move’. Are you using this vector in subsequent calls to Move or something?
Or is it a Rigidbody?
In which case, calling it characterController is kind of confusing since a type with that name exists. But if so… you should check out the ‘AddForce’ method of Rigidbody for applying instantaneous forces to an object.
Is it some other type? 2d? Custom?
I especially wonder because you say you’re doing this:
characterController.velocity.y = mineVelocity
Which if characterController is a CharacterController or Rigidbody, velocity is returned by value, and therefore is a copy. So you can’t set the y member of it and have it impact the given CharacterController/Rigidbody. (that is unless unity in very recent versions added support for the new C# ref properties… but in unity 2021.3.2f1 it’s certainly not like that).