您的位置:首页 > 移动开发 > Unity3D

Unity Official Tutorial OF PICKING UP COLLECTABLES --- Player Movement & Collision Detection

2016-04-30 23:17 381 查看

You will learn

1. Control player move using Rigidbody2d;
2. Collision Detection using OnTriggerEnter2D function;
3. And some important ATTTIONS when collison detection.

Script of PlayerController.cs

ATTENTION PLEASE:
1. We donot use
OnTrigger
in 2D world, which is a
3D world function, just using OnTrigger2Dof2D world instead, attenion please - so doesthe parameter of Collider2D.
2. When collision detection, the gameobject with"some collider" mustcheckable IsTrigger in Inspector panel, if you do wanna
do collision; if not, OnTriggerEnter2D (Collider2D other) will be not workable. See the following demo:



REMEMBER THAT:
1. The wall and "pickups" are all added with " Circle Collider",but if you do wannapick up the "pickups", you mustcheckIs Trigger in Inspector, which
help you MAKE OnTriggerEnter2D workable;

2. If you do not uncheck the "Is Trigger of" Wall's collider, UFO will not run out of wall; otherwise the UFO run out of wall after second movement....

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

private Rigidbody2D rigidbody2d;
public float speed;// speed of UFO

// Use this for initialization
void Start () {
rigidbody2d = GetComponent<Rigidbody2D> ();

}

void FixedUpdate () {
float h = Input.GetAxis ("Horizontal");
float v = Input.GetAxis ("Vertical");

movement (h, v);
}

void movement(float h, float v){

Vector2 movement = new Vector2 (h, v);
rigidbody2d.AddForce (movement * speed * Time.deltaTime);

//Vector3 pos = new Vector3 (h, v, 0);
//GetComponent<Rigidbody2D>().transform.Translate (pos);
}

// We donot use OnTrigger in 2D world, which is a 3D world function,
// just using OnTrigger2D of 2D world instead, attenion please - so does Collider2D.
void OnTriggerEnter2D (Collider2D other){
//Debug.Log ("other name: " + other.gameObject.name );

if ( other.gameObject.CompareTag("PickUp") /*other.gameObject.tag == "PickUp" */) {
other.gameObject.SetActive (false);
//Destroy (other.gameObject);
//score += amount;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: