- Home /
Question by
youngapprentice · Aug 06, 2014 at 09:34 PM ·
raynormalhill
Get Player to 'Stick' to Surface
Hi, all!
So I have these rolling hills and a player. My goal here is to get the player character to:
Align with the surface normal
Move smoothly along the surface normal in either direction
That's it for the time being. My current script works, but sometimes the character will miss a face of the hill mesh and walk right through it, and other times the player won't go all the way down to where the surface actually is, giving a floating effect.
Any suggestions? Have any of you tried this before?
Here is my current script:
public class Locomotion : MonoBehaviour {
public float moveSpeed;
public Transform myCharacter;
private RaycastHit myData;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if( Mathf.Abs ( Input.GetAxis( "Horizontal" ) ) > 0.01){
//If moving
float move = Input.GetAxisRaw( "Horizontal" )*moveSpeed*Time.deltaTime;
//Get a speed and direction
Vector3 startRay = new Vector3( transform.position.x + 0.1f, transform.position.y + 1.0f, transform.position.z );
//Get a ray
Debug.DrawRay( startRay, -transform.up*2.0f );
//Draw it
if( Physics.Raycast( startRay, -transform.up*2.0f, out myData )){
//If there is a hit
myCharacter.transform.rotation = Quaternion.FromToRotation ( Vector3.up, myData.normal );
//Align player to surface normal
//float newSpeed = 0.01f + Vector3.Angle ( Vector3.up, myData.normal)*move;
//Debug.Log ( Vector3.Angle ( Vector3.up, myData.normal));
transform.Translate( move, 0, 0, Space.World );
//Move player
Vector3 newPos = new Vector3( transform.position.x, myData.point.y-0.1f, transform.position.z);
//Stick to face on y axis
transform.position = newPos;
}
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613160016im_/https://answers.unity.com/themes/thub/images/avi.jpg)