Using Raycasts in order to move around

Hello there,

the last days i tried to move my 2D character around with Rigidbodies + Box/Spherecolliders and CharacterController. I wasn’t really happy with them, cause they made me a lot of problems.

Now i thought about using Raycasts, but i kind of don’t know exactly how to start. I read the ScriptReference and tried something like this out:

void IsGrounded()
		if(Physics.Raycast(transform.position, Vray_down, out ray_hit, 20))
				Debug.Log("YOU HIT THE FLOOR!");

i tried it by Moving a Sprite-Object in the Scene-Editor around (while the game is playing) and if it is at the Top of the floor, i get this message. Everything is fine. But, now, HOW exactly can i apply my Object Gravity and tell it to stay on the floor, when the Raycast hits the collider of the floor?

The second thing is: Where exactly starts the RayCast? In the Center of the Gameobject? It would be much easier to handle it, when it would start at the bottom of the Sprite (the feet), can i change that (eventually by script?)


You could add gravity to you player with a rigidbody on it. Just be sure to add a collider to both your player and the floor, so the player stays over it. Another thing that you should keep in mind is to add a tag or a layer to your floor object so you can check if the player is actually colliding with your floor. Something like if (ray_hit.gameObject.tag == “floor”).

For your second question, yes by default the RayCast starts from your object pivot point. There’s a script that allows to change the pivot point from some objects, but it not works with all kind of objects. If your player is just a plane, you will be fine, but if you are using a framework like 2D toolkit, you will have troubles to change the pivot. I have a great tip: If your player have a Collider attached, you could use something like transform.collider.bounds.min to get the values of the min point of your collider. Then you could start your raycast from this point or from a new Vector3 that uses some of this coordinates.

I’ve attached the SetPivot.txt (just change the ext to cs)[4373-setpivot.txt|4373] Script. Just be sure to put this script inside the Editor folder within your solution Folder. (if the folder does not exist, you have to create it)

Hope that helps you.

Thank you for the comment, but it isn’t really what i was looking for. As mentioned in the first post, i don’t want to use rigidbodies or colliders.

But thanks for the tip with the PivotPoint!