- Home /
How would I make my gameobject align to the ground 2d
So, I am trying to make my player align to the collider under it, but it is not working. I have gone about searching for solutions online, but nothing works. Please, can someone show me how?
EDIT: javascript please
Answer by AlienNova · Oct 19, 2017 at 09:41 PM
RaycastHit2D hit = Physics2D.Raycast (player.transform.position, -player.transform.up);
player.transform.rotation = hit.rotation;
This is in C# because I don't know Javascript syntax
Sry for the really late accept. I use c# now, but thanks!
Answer by Ratslayer · Oct 19, 2017 at 09:32 PM
I assume what you mean by "align" is that you want to have your character stand on the object underneath.
To do that, you need to cast a ray downwards from your character's position. If the distance between the character and the hit is smaller than its height / 2, that means it's colliding and you set its position to the collision point + height. Something like this:
RaycastHit hit;
Physics.Raycast(new Ray(transform.position, Vector3.down), out hit);
float distance = (transform.position - hit.point).magnitude;
//you need to determine height of your character yourself
//I assume that character center is in the middle
if (distance <= characterHeight * 0.5f)
{
transform.position = hit.point + Vector3.up * characterHeight;
}
You can put that code into Update function.
I mean like rotate to the normal of the ground beneath it like sonic the hedghog, but still have the ability to jump or leave the ground. ( Javascript)
Your answer
Follow this Question
Related Questions
One 2D Raycast Being Weird While Others Work 0 Answers
Noob Question -- Programming 2d platformer 1 Answer
2D Pixel Platformer Problems 1 Answer