- Home /
Mirror Vector3 with Vector3.Reflect
Hey, I'd like the black ball (enemy) to follow the white ball (player). (image below) I could just add a force to the black ball with the Vector3 to the withe ball, but I want the black ball to counter-steer too so that the ball doesn't roll past the white ball (the white ball is also moving), so I tried to write some code to do so using the Vector3.Reflect method:
Vector3 vecToPlayer = player.transform.position - transform.position;
Vector3 currentDirection = enemyRb.velocity;
Vector3 direction = (vecToPlayer + currentDirection).normalized;
Vector3 mirroredDirection = Vector3.Reflect(-direction, -vecToPlayer);
enemyRb.AddForce(mirroredDirection.normalized * enemySpeed);
Blue = direction Black = vecToPlayer Red = mirroredDirection
But somehow the red Vector3 isn't mirrored to the black Vector3, what did I do wrong or how could I code that in a better way?
Answer by Gustav2302 · Sep 04, 2021 at 12:27 PM
Mirroring a vector is as simple as making it negative. Vector3.reflect is meant to reflect the vector off a surface with the use of a normal vector, so it is irrelevant in this case. The code should look something like this:
Vector3 vecToPlayer = player.transform.position - transform.position;
Vector3 currentDirection = enemyRb.velocity;
Vector3 direction = (vecToPlayer + currentDirection).normalized;
enemyRb.AddForce(-direction * enemySpeed);
Thank you very much for answering! Sadly your code pushes the enemy ball just away from the player.
Mirroring a vector is as simple as making it negative.
I don't think so, if you make it negative, the Vector is reversed not mirrored, I wanted to mirror the Vector over an axis this is what I wanted to achieve with the reflect Method, which I think should be working.
I think i get what you mean now. You want the vector to have the same direction as vecToPlayer, but have the length of direction, right? Then you just have to normalize vecToPlayer, since direction already is normalized:
enemyRb.AddForce(vecToPlayer.normalized * enemySpeed);
if you mean currentDirection instead of direction, then you just have to multiply the normalized vector with the length of currentDirection:
enemyRb.AddForce(vecToPlayer.normalized * currentDirection.magnitude * enemySpeed);
I want the Vector which is mirrored to CurrentDirection when the mirror axis is VecToPlayer like in the picture
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Existence of UnityEngine.Reflect in a project 0 Answers
Reflect bullets in 3D world space 1 Answer