Question by
jktarban · Nov 09, 2015 at 07:02 AM ·
parentchildcollision2d
OnCollisionEnter2D Child to Parent
First of all, I am a newbie creating a 2d platformer...
When I hit "J" the player can push,pull, carry (made the box a child to parent player) the box when collide and "K" to release it. The problem is when i first collide with the box and press "J" nothing happens, I need to move my player a little distance away from the box and collide again to make it happen...
What I need to know is to how the player collide with the box first and when I hit "J" the box automatically becomes the child without moving far away first. Any ideas? sorry
Here are my 2 scripts
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float jumpHeight = 10;
public float moveSpeed = 3;
private PushPull pushpull;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
private bool doubleJumped;
// Use this for initialization
void Start () {
pushpull = new PushPull();
}
void FixedUpdate()
{
grounded = Physics2D.OverlapCircle (groundCheck.position, groundCheckRadius, whatIsGround);
}
// Update is called once per frame
void Update () {
if (grounded)
doubleJumped = false;
if (Input.GetKeyDown (KeyCode.Space) && grounded ) {
GetComponent<Rigidbody2D>().velocity = new Vector2 (GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
Jump ();
}
if (Input.GetKeyDown (KeyCode.J) && grounded ) {
pushpull.isAction(1);
}
if (Input.GetKeyDown (KeyCode.K) && grounded ) {
pushpull.isAction(0);
}
if (Input.GetKey (KeyCode.D)) {
GetComponent<Rigidbody2D>().velocity = new Vector2 (moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
if (Input.GetKey (KeyCode.A)) {
GetComponent<Rigidbody2D>().velocity = new Vector2 (-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
}
public void Jump()
{
GetComponent<Rigidbody2D>().velocity = new Vector2 (GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
}
}
using UnityEngine;
using System.Collections;
public class PushPull : MonoBehaviour {
public GameObject player;
private static int isPullPush = 0;
public int isAction(int actionSignal)
{
isPullPush = actionSignal;
Debug.Log (isPullPush);
return isPullPush ;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(isPullPush == 0)
{
this.gameObject.transform.parent = null;
}
}
void OnCollisionEnter2D(Collision2D coll){
if(coll.gameObject.name=="Player")
{
this.gameObject.transform.parent = player.transform;
}
}
}
Comment
Solved.... used Physics2D.OverlapCircle and assigned points to the side of boxes... this allows me to push/pull boxes when my player is on the side
Your answer