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

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值