iam doing a small demo work using a tutorial. the tutorial is in javascript and iam doing it in c#. the script is about jumping. player has to jump when “w” is pressed, but the player is not staying on the ground surface it is going through the ground. i dont know where am making mistake. i player has rigid body and sphere collider and the ground surface has box collider. the code is below. need some help.
using UnityEngine;
using System.Collections;
public class player_script : MonoBehaviour {
public float speed = 10f;
public float rotationSpeed = 30f;
public GameObject projectile_Prefab;
int score = 0;
int lives = 0;
public float time = 300f;
public float jumpVelocity = 20f;
public float maxSlope = 60f;
public bool grounded = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
time -= Time.deltaTime;
float amtToMove = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
transform.Translate(Vector3.right * amtToMove);
transform.Rotate(amtToMove * rotationSpeed ,0, 0);
if(Input.GetKeyDown("w") && grounded)
{
rigidbody.AddForce(new Vector3(0,jumpVelocity,0), ForceMode.Force);
}
if(Input.GetKeyDown("space"))
{
Vector3 position = new Vector3(transform.position.x + (transform.localScale.x / 2 + 0.5f),transform.position.y);
Instantiate(projectile_Prefab,position, Quaternion.identity);
}
}
void OnCollisionStay(Collision collision)
{
print("iam colliding");
foreach(ContactPoint contact in collision.contacts)
{
if(Vector3.Angle(contact.normal, Vector3.up) < maxSlope)
grounded = true;
}
}
void OnCollisionExit()
{
grounded = false;
}
void OnCollisionEnter(Collision other)
{
if(other.gameObject.name == "coins")
{
score += 10;
Destroy(other.gameObject);
}
}
void OnGUI()
{
GUI.Label(new Rect(10, 10, 100, 20), "SCORE : " + score);
GUI.Label(new Rect(200,10, 100, 20), "LIFE : " + lives);
GUI.Label(new Rect(300,10, 100, 20), "TIME : " + time);
}
}