I am making a top down rpg game. There are two game objects which is my character and a treasure box. Both have box collider 2d attached to them. The problem I am having is OnCollisionStay2D only happened if I keep pressing right, even though the colliders are colliding with each other. I expected it to stay colliding. Below is my code for my character:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
[SerializeField]
private float speed;
private Vector2 playerVector;
private Animator animator;
private Rigidbody2D myRigidBody;
private Vector2 facingLeft = new Vector2(-0.5f, 0.5f);
private Vector2 facingRight = new Vector2(0.5f, 0.5f);
CreateScreenFade blackFade = null;
[SerializeField]
private List<Vector2> firstStagePositionList;
[SerializeField]
PositionManager positionManager;
private int currentRoom = 6;
private bool hasKey = false;
public bool HasKey { set { hasKey = value; } }
public int CurrentRoom
{
get {
return currentRoom;
}
}
// Use this for initialization
void Start () {
playerVector = transform.position;
animator = GetComponent<Animator>();
myRigidBody = GetComponent<Rigidbody2D>();
blackFade = GameObject.Find("CreateBlackScreen").GetComponent<CreateScreenFade>();
}
// Update is called once per frame
void Update () {
PlayerMovingLogic();
}
private void PlayerMovingLogic( )
{
if(!CreateScreenFade.isFading) {
playerVector.x = Input.GetAxisRaw("Horizontal");
playerVector.y = Input.GetAxisRaw("Vertical");
//Player animation logic
if(playerVector.x > 0.0f || playerVector.x < 0.0f || playerVector.y >0.0f || playerVector.y < 0.0f) {
animator.SetBool("Run", true);
} else {
animator.SetBool("Run", false);
}
//Player Direction logic
if(playerVector.x > 0.0f) {
transform.localScale = facingRight;
}else if (playerVector.x < 0.0f) {
transform.localScale = facingLeft;
}
} else {
animator.SetBool("Run", false);
}
}
private void MoveCharacter() {
//myRigidBody.MovePosition(transform.position + playerVector * speed * Time.deltaTime);
}
private void FixedUpdate( )
{
myRigidBody.MovePosition(myRigidBody.position + playerVector * speed * Time.fixedDeltaTime);
}
And also treasure chest code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreasureChest : MonoBehaviour
{
[SerializeField] GameObject spawnObject;
private Animator animator;
private bool isOpened = false;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
private void OnCollisionStay2D(Collision2D collision)
{
if(collision.gameObject.tag == "Player") {
Debug.Log("Collide with chest");
if(Input.GetKeyDown(KeyCode.Space) && !isOpened ) {
isOpened = true;
animator.SetBool("Open", true);
Instantiate(spawnObject, transform.position, Quaternion.identity);
}
}
}
}
Here is the rigidbody2d settings for both
Thank you.