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

来源:互联网 发布:oracle数据库添加字段 编辑:程序博客网 时间:2024/06/05 05:21

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 initializationvoid 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;}}}


0 0
原创粉丝点击