How to detect what I'm standing on?.

Hello, I’m building a character controller using a rigidbody and forces to move, and a raycast to check if we’re grounded.

However, moving platforms are the bane of my existence, I need a way to copy the velocity of the platform that is moving when I’m standing on it.

However, the trouble comes in when I’m trying to detect what I’m standing on exactly, and how to get at variables on the stood object.

This is my script at the moment:

using UnityEngine;
using System.Collections;

public class Walker : MonoBehaviour
{
	public GameObject theCamera;
	public Transform movementBase;
	public float speed;
	public float jumpHeight;
	
	public bool askJump;
	public float distanceToGround;
	private float moveHorizontal;
	private float moveVertical;
	
	void Start()
	{
		distanceToGround = collider.bounds.extents.y;
	}
	
	void Update()
	{
		moveHorizontal = Input.GetAxis ("Horizontal");
		moveVertical = Input.GetAxis ("Vertical");
		
		if(Input.GetKey(KeyCode.Space) && isGrounded())
		{
			askJump = true;
		}
		else
		{
			askJump = false;
		}
	}

	void FixedUpdate()
	{
		Vector3 forwardVel = movementBase.transform.forward * speed * moveVertical;
		Vector3 horizontalVel = movementBase.transform.right * speed * moveHorizontal;
		
		rigidbody.AddForce (forwardVel + horizontalVel, ForceMode.Impulse);
		
		if(askJump == true)
		{
			var jumpVel = rigidbody.velocity;
			jumpVel.y = jumpHeight;
			
			rigidbody.velocity = jumpVel;
		}
	}

	public bool isGrounded()
	{
		return Physics.Raycast(transform.position, -Vector3.up, distanceToGround + 0.1f);
	}
}

So, there it is, I don’t know how to tell what I’m grounded on, so that’s what I need help with.

There is an overload to Physics.Raycast that lets you nab more information regarding what you’re hitting.

RaycastHit hit;
Physics.Raycast(transform.position, Vector3.down, out hit, distanceToGround + 0.1f);

This will let you utilize a RaycastHit to figure out what it was that raycast actually hit, like, say, a moving platform. You can get a Collider out of hit (via hit.collider), and from there extrapolate the connected GameObject.

Just a note: hit.collider will return the Collider that the raycast hit. This is the other GameObject, not your character.