I am trying to make a snowboard game just for fun. I am no programmer, I am just some one playing with Unity. I am trying to align the board only on local x to the ground. It aligns well when I start the script but as soon as I make the board rotate it acts very weird. I am very bad with quaternions :(. If you know a great reference to learn quaternions and math physics for games please let me know ! The scene is a blue board with the following script applied to it and a floor.
Here is my code, I know there is A LOT to improve. But the orientation to ground part is what bugs me the most right now…
using UnityEngine;
using System.Collections;
public class boardSim : MonoBehaviour {
public float airFriction=1f;
public float snowFriction=4f;
public float gravity=-1.8f;
public bool isGrounded=true;
public float upSpeed=0f;
public float groundDistance;
public float speed;
public float friction;
public GameObject raycaster;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//gravity on the board
RaycastHit gravityHit;
Physics.Raycast(transform.position, -Vector3.up, out gravityHit);
groundDistance=gravityHit.distance;
//orientation to ground
RaycastHit hit;
Physics.Raycast(transform.position, -Vector3.up, out hit);
Quaternion hitRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
// the last line makes no sense, but it could be translated to:
Quaternion rot = transform.rotation; // copy rotation to an aux variable...
rot.x = hitRotation.x; // change the x component in that variable...
//rot.z = hitRotation.z; // change the x component in that variable...
transform.localRotation = rot; // then assign it to rotation
if (groundDistance>0.2){
upSpeed=gravity;
friction=airFriction;
isGrounded=false;
}
else{
upSpeed=0f;
friction=snowFriction;
isGrounded=true;
}
//speed calculation of the board
if (Input.GetButton("boardMotor")){
speed+=5f*Time.deltaTime;
}
else{
speed-=friction*Time.deltaTime;
}
speed=Mathf.Clamp(speed,0,100);
//edging of the board
Debug.Log(Input.GetAxis("boardEdge"));
transform.Rotate(Vector3.up, Time.deltaTime*Input.GetAxis("boardEdge")*100);
//applying translation
transform.Translate(0, upSpeed*Time.deltaTime, speed*Time.deltaTime, transform);
}
}