Reputation: 11
I'm creating a mobile game in unity 3D where you have to jump from one wall to another dodging spikes. I've got in fact two problems, both with collisions. (btw. the game looks like its vertical, but in fact the camera is just rotated :) This is my player controller:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Rigidbody rgb;
public float jumpStrenght;
public bool walled;
public bool jump;
void Start()
{
}
void FixedUpdate()
{
if(Input.GetButtonDown("Jump"))
{
Jump();
}
if(jump)
{
Jump();
}
if (walled)
{
rgb.isKinematic = true;
}
}
public void Jump()
{
if (walled)
{
walled = false;
rgb.isKinematic = false;
rgb.AddForce(transform.up * jumpStrenght, ForceMode.Impulse);
}
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.CompareTag("Wall"))
{
walled = true;
}
//print("col enter");
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.CompareTag("WallEnd"))
{
walled = false;
}
//print("trigger enter");
}
void OnCollisionExit(Collision col)
{
//print("col exit");
}
public void OnPress()
{
jump = true;
}
public void OnRelese()
{
jump = false;
}
}
(sorry for messy code :)
OnCollisionExit wouldn't trigger when falling on the ledge (https://i.sstatic.net/NUbpI.png) I'm setting the rigidbody to kinematic to handle the situation when player is sticking to the celling
The collision with spikes won't trigger if the player isn't falling on them from up. (The game is still playing) This is the code for spikes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Danger : MonoBehaviour
{
void OnCollisionEnter(Collision col)
{
print("col");
if(col.gameObject.GetComponent<PlayerController>())
{
print("colPl");
GameManager.instance.EndGame();
}
}
}
If anything is unclear I'll be looking there every day to check for responses and I'll do my best to explain it beter. I'd be really happy to get this bug fixed because I was working on it for almost a week.
The OnCollisionExit method gets called even when player enters collision and isn't called at all when exiting collision. OnCollisionEnter isn't called when already colliding with ground.
Upvotes: 1
Views: 150
Reputation: 1535
My understanding OnCollisionExit is not being called, it could be due to the player's Rigidbody being set to kinematic when in contact with the wall.
So here is what I think it should help. Instead of setting the Rigidbody to kinematic, try setting the Rigidbody's velocity to zero. Remove the lines that rgb.isKinematic = true;
Try the below and see if it solve your issue.
void FixedUpdate()
{
if (Input.GetButtonDown("Jump"))
{
Jump();
}
if (jump)
{
Jump();
}
if (walled)
{
rgb.useGravity = false;
rgb.velocity = Vector3.zero;
}
else
{
rgb.useGravity = true;
}
}
public void Jump()
{
if (walled)
{
walled = false;
rgb.AddForce(transform.up * jumpStrenght, ForceMode.Impulse);
}
}
Upvotes: 0