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);
}
}
previously i used only if(jump) and it worked. is kinematics are all disabled. this code is a from a video tutorial. i recreated it while watching it. i dont know whether there is a link to the code, but i'll try to find the link. thank for the suggestion.
– galaboyprint("iam colliding"); Does this output to the console at all?
– verenionno it's not.
– galaboyOkay. So, in that case grounded will ALWAYS be false because OnCollisionStay() is not being called. That might be because your colliders / rigidbodies are not setup correctly. HOWEVER, I have just found this, and it looks like it's the same code. Try restarting Unity. [http://answers.unity3d.com/questions/142618/oncollisionstay-is-not-returning-anything.html][1] [1]: http://answers.unity3d.com/questions/142618/oncollisionstay-is-not-returning-anything.html
– verenionthanks for the link. it works now by restarting unity and recreated the player with new player.
– galaboy