找回密碼
 注冊帳號

掃一掃,訪問微社區

collider.oncollisionenter 進入碰撞

2015-1-4 17:37| 發布者: 楊炎| 查看: 2615| 評論: 0|原作者: 蠻牛|來自: unity3d腳本manual

摘要: collider.oncollisionenter 進入碰撞functiononcollisionenter(collisioninfo:collision) : voiddescription描述oncollisionenter is called when this collider/rigidbody has begun touching another rigidbody/co ...

collider.oncollisionenter 進入碰撞

functiononcollisionenter(collisioninfo:collision) : void

description描述

oncollisionenter is called when this collider/rigidbody has begun touching another rigidbody/collider.

當collider/rigidbody開始觸動另一個rigidbody/collider時oncollisionenter被調用。

in contrast to ontriggerenter, oncollisionenter is passed thecollisionclass and not a collider. thecollisionclass contains information about contact points, impact velocity etc. if you don't use collisioninfo in the function, leave out the collisioninfo parameter as this avoids unneccessary calculations. note that collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached.

相比ontriggerenter,oncollisionenter傳遞collision類而不是collider。collision類包含接觸點,碰撞速度等信息。在這個函數如果你不使用collisioninfo,刪去collisioninfo參數以避免不必要的計算。注意,當其中至少一個碰撞盒附加非動力學剛體時碰撞事件才會發送。

c#

javascript

using unityengine;

using system.collections;

public class example :monobehaviour{

void oncollisionenter(collision collision) {

foreach (contactpoint contact in collision.contacts) {

debug.drawray(contact.point, contact.normal, color.white);

}

if (collision.relativevelocity.magnitude > 2)

audio.play();

}

}

function oncollisionenter(collision : collision) {

// debug-draw all contact points and normals

//調試繪制全部的接觸點和法線

for (var contact : contactpoint in collision.contacts) {

debug.drawray(contact.point, contact.normal, color.white);

}

// play a sound if the coliding objects had a big impact.

//如果碰撞物體有一個更大的撞擊就播放聲音

if (collision.relativevelocity.magnitude > 2)

audio.play();

}

另一個例子:

c#

javascript

using unityengine;

using system.collections;

public class example :monobehaviour{

publictransformexplosionprefab;

void oncollisionenter(collision collision) {

contactpoint contact = collision.contacts[0];

quaternion rot = quaternion.fromtorotation(vector3.up, contact.normal);

vector3 pos = contact.point;

instantiate(explosionprefab, pos, rot);

destroy(gameobject);

}

}

// a grenade

//一個手榴彈

// - instantiates a explosion prefab when hitting a surface

//當撞擊表面時實例化一個爆炸預設

// - then destroys itself

//然后銷毀它們

var explosionprefab :transform;

function oncollisionenter(collision : collision) {

// rotate the object so that the y-axis faces along the normal of the surface

//旋轉物體,以便y軸方向沿著表面的法線

var contact : contactpoint = collision.contacts[0];

var rot : quaternion = quaternion.fromtorotation(vector3.up, contact.normal);

var pos :vector3= contact.point;

instantiate(explosionprefab, pos, rot);

// destroy the projectile

//銷毀物體

destroy (gameobject);

}

相關閱讀

文章點評
相關文章
女校游泳队彩金