- Home /
Collider Failing to notice
Hello! I'm working with Unity 2D, and I essentially want to have something happen to the player when they collide with this object (in this case, a spring). I haven't gotten the objects to recognize each other yet, though. Here is the line of code I have in my spring:
void onCollisionEnter2D (Collision2D collision){
Debug.Log ("collided with player");
}
My player has a Rigidbody2D and a Box Collider 2D with 'is trigger' unchecked. If it is checked, it just falls right through the environment. I've tried adding a second Box Collider 2D to the object with is trigger checked, but that doesn't do the trick.
Just for reference, here is the code currently on the player object:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public Transform groundCheck;
public Vector2 playerPos;
public Vector2 groundPos;
public bool canJump;
public bool grounded = false;
public bool sprung = false;
public float jumpForce = 1000f;
public float moveForce = 200f;
public float maxSpeed = 15f;
public float springForce = 3000f;
public int airPenalty = 50;
// Use this for initialization
void Start () {
groundCheck = transform.Find("GroundCheck");
}
// Update is called once per frame
void Update () {
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
sprung = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Spring"));
if(Input.GetButtonDown("Jump") && grounded)
canJump = true;
}
void FixedUpdate(){
float h = Input.GetAxis("Horizontal");
if (h * rigidbody2D.velocity.x < maxSpeed) {
if(grounded)
rigidbody2D.AddForce (Vector2.right * h * moveForce);
else
rigidbody2D.AddForce (Vector2.right * h * moveForce / airPenalty );
}
if(Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)
rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
if (sprung) {
//rigidbody2D.AddForce (Vector2.up * springForce);
//This works, but I want the logic to live in the other object.
}
///Jumping
if(canJump)
{
// Add a vertical force to the player.
rigidbody2D.AddForce(new Vector2(0f, jumpForce));
// Make sure the player can't jump again until the jump conditions from Update are satisfied.
canJump = false;
}
}
}
Thanks everyone!
Forgot to mention: The spring itself also has a Box Collider2D. It doesn't work with both is trigger checked and unchecked.
Do you have is$$anonymous$$inesmatic checked on Player rigidbody component (in which case it does not count as a collision)
I do not have "is $$anonymous$$inematic" checked. It tends to fall through my Geometry if I do.
Your answer
Follow this Question
Related Questions
Enable Specific Collider when Another is Triggered. 1 Answer
Why does my trigger only fire one time? 0 Answers
How to calculate a Collider2D's bounds 0 Answers
Ignore Collision for 2d Collider 2 Answers
2D/Top Down Enemy Follow 0 Answers