I’m developing an infinite sidescroller, where the player has to avoid a variety of traps and survive as long as possible for a high score. The problem I’m having is with my collision detection- occasionally, a collision will be detected much too early, killing the player when they had clearly not touched a trap.
Here’s the code governing the player movement (C#):
void FixedUpdate ()
{
float x = speed * Time.deltaTime;
Player.rigidbody.AddForce(0, FallSpeed * -1, 0);
if (transform.position.y > 40)
{
Player.rigidbody.AddForce(0, FallSpeed * -10, 0);
}
if (transform.position.x >= 1000)
{
float currentY = transform.position.y;
float restartX = 0;
transform.position = new Vector3(restartX, currentY, 0);
}
transform.Translate(x, 0, 0);
if (Input.GetKeyDown(KeyCode.Space))
{
Player.rigidbody.Sleep();
Player.rigidbody.AddForce(0, JumpForce, 0);
}
if (Input.GetKeyDown(KeyCode.X))
{
isCharging = 1;
StartCoroutine(chargeTimer());
}
}
IEnumerator chargeTimer()
{
float oldSpeed = speed;
float oldFall = FallSpeed;
transform.rigidbody.Sleep();
FallSpeed = 0;
speed = chargeSpeed;
yield return new WaitForSeconds(chargeDuration);
speed = oldSpeed;
FallSpeed = oldFall;
isCharging = 0;
}
I use the sleeps to stop the forces currently acting on the rigid body before applying new ones, I wanted the jump to not observe gravity or current downward force applied to it.
And here’s the collision detection code (currently attached to the trap objects in my scene)
public GameObject Player;
public GameObject Trap;
public GameObject mainCamera;
void OnCollisionEnter(Collision collision)
{
ninjaScroll script;
script = Player.GetComponent<ninjaScroll>();
if (script.isCharging == 1)
{
Destroy(Trap);
}
else
{
mainCamera.transform.parent = null;
Destroy(Player);
StartCoroutine(MyLoadLevel(5, 0));
}
}
IEnumerator MyLoadLevel(float delay, int level)
{
yield return new WaitForSeconds(delay);
Application.LoadLevel(level);
}
Thanks so much! That makes total sense. I've been writing c# for all of 3 weeks now so I'm still getting a lot of this sorted out. Totally resolved the issue :)
– anon8133141