- Home /
Make Gameobject Stand On Surface Facing Certain Direction
I want to make a biped character stand on any surface I click on.
Surfaces have up vectors of any of positive or negative X,Y,Z. So imagine a cube with each face being a gameobject whose up vector pointing directly away from the cube.
If my character is facing "forward" and I click on a surface which is to the left or right of me ( left or right walls), I want my character to now be standing on that surface but still be facing in the direction he initially was. If I click on a wall which is in the forward path of my character i want him to now be standing on that surface and his forward to now be what was once "up" relative to my character. Here is the code I am working with now.
void Update()
{
if (Input.GetMouseButtonUp (0)) {
RaycastHit hit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
Vector3 upVectBefore = transform.up;
Vector3 forwardVectBefore = transform.forward;
Quaternion rotationVectBefore = transform.rotation;
Vector3 hitPosition = hit.transform.position;
transform.position = hitPosition;
float lookDifference = Vector3.Distance(hit.transform.up, forwardVectBefore);
if(Vector3.Distance(hit.transform.up, upVectBefore) < .23) //Same normal
{
transform.rotation = rotationVectBefore;
}
else if(lookDifference > 1.412 && lookDifference <= 1.70607) //side wall
{
transform.up = hit.transform.up;
transform.forward = forwardVectBefore;
}
else //head on wall
{
transform.up = hit.transform.up;
transform.forward = upVectBefore;
}
}
}
}
The first case "Same normal" works fine, however the other two do not work as I would like them to. Sometimes my character is laying down on the surface or on the wrong side of the surface. Does anyone know nice way of solving this problem?
well, khm khm khm, ... did you even search?
what you need is:
OR even more:
as I'm in good mood I'm going to even copy paste the code here.
Ray ray = new Ray(transform.position, Planet.position - transform.position));
RaycastHit hit;
if (Planet.collider.Raycast(ray, out hit, Vector3.Distance(Planet.position, transform.position) ) ){
transform.rotation = Quaternion.LookRotation( Vector3.Cross(transform.right, hit.normal) , hit.normal);
}
OFC the Planet.position is your object from witch you want to be around.
NOTE if you have a mesh collider and it will be a bit uneven you won't be facing towards the center of it.
Your answer
Follow this Question
Related Questions
Connecting transform with Vector3 4 Answers
Change transform.forward while slerping rotations around the transform.forward axis 1 Answer
Object wont rotate in the opposite direction 1 Answer
How to make Y-Axis face away from a position? 2 Answers
How do I make gameObject.transform.rotation.z equal to a set float value? 2 Answers