unityunity box colliderr可以旋转吗

Unity3D实现点击物体旋转 - 博客频道 - CSDN.NET
美丽的旭哥(C/C++)
心在哪里,成功就在哪里
分类:unity3D
using UnityE
using System.C
public class roated : MonoBehaviour {
private float RoatedSpeed = 1000.0F;
void Start () {
// Update is called once per frame
void Update () {
if(Input.GetMouseButton(0))
float y = 0;
y = Input.GetAxis(&Mouse X&)*RoatedSpeed*Time.deltaT
gameObject.transform.Rotate(new Vector3(0,y,0));
void OnMouseDown()
Debug.Log(&collider&);
void OnMouseUp()
Debug.Log(&Out of collider&);
排名:千里之外
(3)(2)(17)(11)(1)Unity 基础 - 刚体和 Collider - 推酷
Unity 基础 - 刚体和 Collider
Unity 中的 物理引擎能够真实的模拟现实世界的物理效果,在 Unity 中使用的是 NVIDIA 的 PhysX 物理引擎,在 Unity 中使用 Rigidbody 让游戏对象受物理引擎控制。
打开 Unity ,新建一个 Plane,将它的 transform reset 一下,让它处在原点的位置。为了方便查看,可以给这个 Plane 添加一个材质球,设置一个颜色,然后创建一个 Cube 物体,
运行游戏,并不会有什么变化。
然后,给 Cube 物体添加 Rigidbody 属性:
再重新运行游戏,如下图:
会发现 Cube 物体受到重力的影响,落到 Plane 上。
然后在看一下 Rigidbody 属性:
mass :质量,默认为 1Drag :空气阻力,默认为 0Angular Drag :当物体旋转时收到的阻力,默认为 0.05Use Grivity :是否使用重力,默认选中Is Kineatic :是否使用运动学,默认不选中(和 transform 不能同时使用),如果选中,则不会受到重力影响Interpolate :差值,None(无),Interpolate(内差值,从之前的一帧,推测下一帧的位置),Extrapolate(外差值,从下一帧推测上一帧位置),Collision Detection :碰撞检测,Discrete(离散检测),Continuous(连续碰撞检测),Continuous Dynamic(连续动态碰撞检测)Constraints :约束Freeze Position :冻结位置,如果勾选 y,则不会下落Freeze Rotation :冻结旋转
接着创建一个 Sphere 物体,给它添加刚体属性,然后运行,之后用 Sphere 碰撞 Cube:
如果冻结旋转属性,则落到 Plane 上之后,就不会发生旋转了。
接着选中 Cube ,给 Cube 添加一个脚本,添加下面的代码,可以获取属性面板里的所有属性:
Rigidbody rb = GetComponent &Rigidbody&();float mass = rb.float drag = rb.// ...``` ### 二、刚体和碰撞体#### 1.刚体
using UnityEusing System.C
public class cubeScript : MonoBehaviour {
// Use this for initialization
void Start () {
rb = GetComponent &Rigidbody&();
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.Alpha1)) {
// 给当前游戏对象添加一个力
// rb.AddForce (new Vector3(0.0f, 10.0f, 0.0f));
// 给当前游戏对象添加 力矩/扭矩,扭矩可以使物体旋转
// rb.AddTorque (new Vector3(0.0f, 10.0f, 0.0f));
// 给当前游戏对象在指定的位置上添加一个力
// rb.AddForceAtPosition (new Vector3(0.0f, 10.0f, 0.0f), new Vector3(0.5f, 0.5f, 0.5f));
// 给当前游戏对象在某个点添加一个爆炸力,不能持续添加,只能炸一下
rb.AddExplosionForce (1500.0f, Vector3.zero, 5.0f);
运行效果如下:![Upload 碰撞.gif failed. Please try again.]#### 2.ColliderCollider 组件的主要功能是进行碰撞检测,使用刚体时,一般都会和 Collider 共同使用。创建游戏物体时都会默认创建一个 Box Collider (盒型碰撞器),在 Cube 的边框上,主要作用是界定一个范围,也就是一个包围盒,来检测是否发生碰撞![盒型碰撞器](http://upload-images.jianshu.io/upload_images/1116587-dac79.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
Is Trigger :是否具有触发效果,默认不选中
Material : 物理材质(摩擦力,弹力)
Center :边框的位置
Size :边框的大小
![移动Box的center.gif](http://upload-images.jianshu.io/upload_images/40c.gif?imageMogr2/auto-orient/strip)#### 3.碰撞和触发事件发生碰撞的两个物体必须带有 Collider ,发生碰撞的两个物体至少有一个带有刚体,发生碰撞的两个物体必须有相对运动。
using UnityEusing System.C
public class redScript : MonoBehaviour {
// Use this for initialization
void Start () {
// Update is called once per frame
void Update () {
// 触发器的三个事件
// 进入触发范围会调用一次
void onTriggerEnter (Collider other) {
// 当持续在触发范围内发生时调用
void onTriggerStay (Collider other) {
// 离开触发范围会调用一次
void onTriggerExit (Collider other) {
// -------
//碰撞相关的三个方法
// 碰撞开始会调用一次
void onCollisionEnter (Collision other) {
// 当碰撞持续发生时调用
void onCollisionStay (Collision other) {
//检测和谁发生碰撞
if (string.Equals (&Cube2&, other.gameObject.name)) {
print(&产生了火花&);
// 碰撞结束会调用一次
void onCollisionExit (Collision other) {
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致Unity3D技术开发之物体的惯性旋转详解_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
Unity3D技术开发之物体的惯性旋转详解
上传于|0|0|暂无简介
阅读已结束,如果下载本文需要使用0下载券
想免费下载更多文档?
定制HR最喜欢的简历
你可能喜欢什么是Collider
  碰撞器组件在Unity引擎中触发物理碰撞的最基本的条件。
  可以这样说,假如一个游戏中没有物理碰撞系统是不可能的。
什么是Rigidbody
  通过物理模拟的控制对象的位置。
  Rigidbody组件添加到一个对象将其运动的控制下统一的物理引擎。即使没有添加任何代码,Rigidbody对象将由重力向下拉,将反应与传入的对象如果正确的对撞机碰撞组件也存在。
  Rigidbody也有脚本API,允许您力量应用于对象和物理现实的方式控制它。例如,一辆汽车的行为可以指定在力量方面应用的轮子。鉴于这种信息,物理引擎可以处理大多数汽车运动的其他方面,所以它将加速实际和正确应对冲突。
  &&通常会在脚本的FixedUpdate函数中改变Rigidbody设置。原因是防止在更新时时间不配合帧更新的步骤。
  FixedUpdate称为每个物理之前立即更新,所以任何更改将会有直接处理。
  开始使用Rigidbody时常见的问题是,游戏中模拟的物理系统似乎在&慢运动&运行。这实际上是由于规模用于您的模型。默认的重力设置假设一个世界单元对应于一米的距离。与非现实的游戏,是没有多大的区别,如果您的模型都是100单位长但使用物理时,他们将被视为非常大的对象。如果大规模用于对象应该是小,他们似乎会非常缓慢&&物理引擎认为他们非常大对象摔倒非常大的距离。考虑到这一点,一定要保持你的对象在现实生活中或多或少的规模(所以汽车应该大约4单位= 4米)。
Collider的用法
碰撞器常用的方法
OnCollisionEnter
//当另一个游戏对象的刚体或者碰撞器,碰撞到本游戏对象的碰撞器组件时,会调用这个方法...
Collider.OnCollisionEnter(Collision)
void OnCollisionEnter(Collision collision) {
//遍历碰撞到该游戏对象的碰撞器组件的所有对象...
foreach (ContactPoint contact in collision.contacts) {
Debug.DrawRay(contact.point, contact.normal, Color.white);
OnCollisionExit
//当另一个游戏对象已经离开当前游戏对象的刚体或者是碰撞器组建时会调用这个方法...
Collider.OnCollisionExit(Collision)
OnCollisionStay
//当另一个游戏对象的碰撞器一直停留在当前游戏对象上的刚体或者碰撞器时,会调用这个方法...
Collider.OnCollisionStay(Collision)
注意:当把碰撞器Collisider组件的触发器属性设置为true时,在脚本中会调用如下三个方法
OnTriggerEnter
//需要注意的是,触发器回调方法的参数是Collider类型
Collider.OnTriggerEnter(Collider)
OnTriggerExit
Collider.OnTriggerExit(Collider)
OnTriggerStay
Collider.OnTriggerEnter(Collider)
Rigidbody的用法
Rigidbody的成员变量&
成员变量名称
成员变量的作用
angularDrag
游戏对象对应的角阻力
angularVelocity
游戏对象的角速度向量&
centerOfMass
相对于游戏对象自身的坐标系统的重心位置
collisionDetectionMode
游戏对象刚体组件的碰撞检测模式
constraints
用来约束游戏对象在某些条件上是可以自由跟随Unity物理系统移动的
detectCollisions
是否启用游戏对象的碰撞检测功能。默认都是开启的。
游戏对象在运动时的阻力
freezeRotation
用来约束游戏对象是否会被Unity物理系统影响自身的旋转
isKinematic
用来控制游戏对象的刚体是否会收到Unity物理系统的影响
用来表示游戏对象刚体的质量
maxAngularVelocity
用来表示游戏对象的最大角速度
游戏对象刚体组件所处在的位置坐标
游戏对象刚体组件已经产生的坐标旋转
sleepAngularVelocity
用来表示当游戏对象的角速度小于临界值时就停止。默认值0.14
sleepVelocity
用来表示当游戏对象的运行速度小于临界值时就停止。默认值0.14
useGravity
用来表示当前游戏对象是否收到重力系统的影响
用来表示当前游戏对象的刚体的运行速度
worldCenterOfMass
相对于世界的坐标系统的重心位置
在Unity开发工具中使用到的组件接口面板
Rigidbody常用的方法
//为rigidbody添加一个方向力。因此,rigidbody将开始移动。
void AddForce(Vector3 force, ForceMode mode = ForceMode.Force);
//在FixedUpdate函数中,为rigidbody添加10个单位向上的方向力
void FixedUpdate() {
rigidbody.AddForce(Vector3.up * 10);
AddForceAtPosition
//在一个位置为Rigidbody添加一个力.
void AddForceAtPosition(Vector3 force, Vector3 position, ForceMode mode = ForceMode.Force);
//ApplyForce函数是个自定义函数,用来对一个刚体对象施加一个方向力
void ApplyForce(Rigidbody body) {
//计算当前游戏对象和刚体参数游戏对象所处位置的方向
Vector3 direction = body.transform.position - transform.
//在当前游戏对象所处的位置,为body参数施加1个单位的方向力
body.AddForceAtPosition(direction.normalized, transform.position);
//为刚体组件添加一个力矩,使该游戏对象产生旋转的速度...
void AddTorque(Vector3 torque, ForceMode mode = ForceMode.Force);
//为游戏对象添加一个10个单位的旋转力...
void FixedUpdate() {
rigidbody.AddTorque(Vector3.up * 10);
形成的效果如下
AddRelativeTorque
//添加一个扭矩rigidbody相对rigidbody自身的坐标系统
void AddRelativeTorque(Vector3 torque, ForceMode mode = ForceMode.Force);
//相对于游戏对象自身的坐标系统,添加10个单位沿着y轴正向旋转的力
void FixedUpdate()
rigidbody.AddRelativeTorque(Vector3.up * 10);
那么在Unity物理引擎系统里两个常用的组件,Collider和Rigidbody就到这里。
希望大家多多支持。
阅读(...) 评论()请问如何让主角左右移动变为左右旋转_unity吧_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:19,014贴子:
请问如何让主角左右移动变为左右旋转收藏
#pragma strict#pragma implicit#pragma downcast// Does this script currently respond to input?var canControl : boolean =var useFixedUpdate : boolean =// For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.// Very handy for organization!// The current global direction we want the character to move in.@System.NonSerializedvar inputMoveDirection : Vector3 = Vector3.// Is the jump button held down? We use this interface instead of checking// for the jump button directly so this script can also be used by AIs.@System.NonSerializedvar inputJump : boolean =class CharacterMotorMovement {// The maximum horizontal speed when movingvar maxForwardSpeed : float = 10.0;var maxSidewaysSpeed : float = 10.0;var maxBackwardsSpeed : float = 10.0;// Curve for multiplying speed based on slope (negative = downwards)var slopeSpeedMultiplier : AnimationCurve = AnimationCurve(Keyframe(-90, 1), Keyframe(0, 1), Keyframe(90, 0));// How fast does the character change speeds?
Higher is faster.var maxGroundAcceleration : float = 30.0;var maxAirAcceleration : float = 20.0;// The gravity for the charactervar gravity : float = 10.0;var maxFallSpeed : float = 20.0;// For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.// Very handy for organization!// The last collision flags returned from controller.Move@System.NonSerializedvar collisionFlags : CollisionF // We will keep track of the character's current velocity,@System.NonSerializedvar velocity : Vector3;// This keeps track of our current velocity while we're not grounded@System.NonSerializedvar frameVelocity : Vector3 = Vector3.@System.NonSerializedvar hitPoint : Vector3 = Vector3.@System.NonSerializedvar lastHitPoint : Vector3 = Vector3(Mathf.Infinity, 0, 0);}var movement : CharacterMotorMovement = CharacterMotorMovement();enum MovementTransferOnJump {None, // The jump is not affected by velocity of floor at all.InitTransfer, // Jump gets its initial velocity from the floor, then gradualy comes to a stop.PermaTransfer, // Jump gets its initial velocity from the floor, and keeps that velocity until landing.PermaLocked // Jump is relative to the movement of the last touched floor and will move together with that floor.}// We will contain all the jumping related variables in one helper class for clarity.class CharacterMotorJumping {// Can the character jump?var enabled : boolean =// How high do we jump when pressing jump and letting go immediatelyvar baseHeight : float = 1.0;// We add extraHeight units (meters) on top when holding the button down longer while jumpingvar extraHeight : float = 4.1;// How much does the character jump out perpendicular to the surface on walkable surfaces?// 0 means a fully vertical jump and 1 means fully perpendicular.var perpAmount : float = 0.0;// How much does the character jump out perpendicular to the surface on too steep surfaces?// 0 means a fully vertical jump and 1 means fully perpendicular.var steepPerpAmount : float = 0.5;// For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.// Very handy for organization!// Are we jumping? (Initiated with jump button and not grounded yet)// To see if we are just in the air (initiated by jumping OR falling) see the grounded variable.@System.NonSerializedvar jumping : boolean =@System.NonSerializedvar holdingJumpButton : boolean =// the time we jumped at (Used to determine for how long to apply extra jump power after jumping.)@System.NonSerializedvar lastStartTime : float = 0.0;@System.NonSerializedvar lastButtonDownTime : float = -100;@System.NonSerializedvar jumpDir : Vector3 = Vector3.}var jumping : CharacterMotorJumping = CharacterMotorJumping();class CharacterMotorMovingPlatform {var enabled : boolean =var movementTransfer : MovementTransferOnJump = MovementTransferOnJump.PermaT@System.NonSerializedvar hitPlatform : T@System.NonSerializedvar activePlatform : T@System.NonSerializedvar activeLocalPoint : Vector3;@System.NonSerializedvar activeGlobalPoint : Vector3;@System.NonSerializedvar activeLocalRotation : Q@System.NonSerializedvar activeGlobalRotation : Q@System.NonSerializedvar lastMatrix : Matrix4x4;@System.NonSerializedvar platformVelocity : Vector3;@System.NonSerializedvar newPlatform :}var movingPlatform : CharacterMotorMovingPlatform = CharacterMotorMovingPlatform();class CharacterMotorSliding {// Does the character slide on too steep surfaces?var enabled : boolean =// How fast does the character slide on steep surfaces?var slidingSpeed : float = 15;// How much can the player control the sliding direction?// If the value is 0.5 the player can slide sideways with half the speed of the downwards sliding speed.var sidewaysControl : float = 1.0;// How much can the player influence the sliding speed?// If the value is 0.5 the player can speed the sliding up to 150% or slow it down to 50%.var speedControl : float = 0.4;}var sliding : CharacterMotorSliding = CharacterMotorSliding();@System.NonSerializedvar grounded : boolean =@System.NonSerializedvar groundNormal : Vector3 = Vector3.private var lastGroundNormal : Vector3 = Vector3.private var tr : Tprivate var controller : CharacterCfunction Awake () {controller = GetComponent (CharacterController);tr =}private function UpdateFunction () {// We copy the actual velocity into a temporary variable that we can manipulate.var velocity : Vector3 = movement.// Update velocity based on inputvelocity = ApplyInputVelocityChange(velocity);// Apply gravity and jumping forcevelocity = ApplyGravityAndJumping (velocity);// Moving platform supportvar moveDistance : Vector3 = Vector3.if (MoveWithPlatform()) {var newGlobalPoint : Vector3 = movingPlatform.activePlatform.TransformPoint(movingPlatform.activeLocalPoint);moveDistance = (newGlobalPoint - movingPlatform.activeGlobalPoint);if (moveDistance != Vector3.zero)controller.Move(moveDistance);// Support moving platform rotation as well:
var newGlobalRotation : Quaternion = movingPlatform.activePlatform.rotation * movingPlatform.activeLocalR
var rotationDiff : Quaternion = newGlobalRotation * Quaternion.Inverse(movingPlatform.activeGlobalRotation);
var yRotation = rotationDiff.eulerAngles.y;
if (yRotation != 0) {
// Prevent rotation of the local up vector
tr.Rotate(0, yRotation, 0);
}}// Save lastPosition for velocity calculation.var lastPosition : Vector3 = tr.// We always want the movement to be framerate independent.
Multiplying by Time.deltaTime does this.var currentMovementOffset : Vector3 = velocity * Time.deltaT// Find out how much we need to push towards the ground to avoid loosing grouning// when walking down a step or over a sharp change in slope.var pushDownOffset : float = Mathf.Max(controller.stepOffset, Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude);if (grounded)currentMovementOffset -= pushDownOffset * Vector3.// Reset variables that will be set by collision functionmovingPlatform.hitPlatform =groundNormal = Vector3.
// Move our character!movement.collisionFlags = controller.Move (currentMovementOffset);movement.lastHitPoint = movement.hitPlastGroundNormal = groundNif (movingPlatform.enabled && movingPlatform.activePlatform != movingPlatform.hitPlatform) {if (movingPlatform.hitPlatform != null) {movingPlatform.activePlatform = movingPlatform.hitPmovingPlatform.lastMatrix = movingPlatform.hitPlatform.localToWorldMmovingPlatform.newPlatform =}}// Calculate the velocity based on the current and previous position.
// This means our velocity will only be the amount the character actually moved as a result of collisions.var oldHVelocity : Vector3 = new Vector3(velocity.x, 0, velocity.z);movement.velocity = (tr.position - lastPosition) / Time.deltaTvar newHVelocity : Vector3 = new Vector3(movement.velocity.x, 0, movement.velocity.z);// The CharacterController can be moved in unwanted directions when colliding with things.// We want to prevent this from influencing the recorded velocity.if (oldHVelocity == Vector3.zero) {movement.velocity = new Vector3(0, movement.velocity.y, 0);}else {var projectedNewVelocity : float = Vector3.Dot(newHVelocity, oldHVelocity) / oldHVelocity.sqrMmovement.velocity = oldHVelocity * Mathf.Clamp01(projectedNewVelocity) + movement.velocity.y * Vector3.}if (movement.velocity.y & velocity.y - 0.001) {if (movement.velocity.y & 0) {// Something is forcing the CharacterController down faster than it should.// Ignore thismovement.velocity.y = velocity.y;}else {// The upwards movement of the CharacterController has been blocked.// This is treated like a ceiling collision - stop further jumping here.jumping.holdingJumpButton =}}// We were grounded but just loosed groundingif (grounded && !IsGroundedTest()) {grounded =// Apply inertia from platformif (movingPlatform.enabled &&(movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer ||movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)) {movement.frameVelocity = movingPlatform.platformVmovement.velocity += movingPlatform.platformV}SendMessage(&OnFall&, SendMessageOptions.DontRequireReceiver);// We pushed the character down to ensure it would stay on the ground if there was any.// But there wasn't so now we cancel the downwards offset to make the fall smoother.tr.position += pushDownOffset * Vector3.}// We were not grounded but just landed on somethingelse if (!grounded && IsGroundedTest()) {grounded =jumping.jumping =SubtractNewPlatformVelocity();SendMessage(&OnLand&, SendMessageOptions.DontRequireReceiver);}// Moving platforms supportif (MoveWithPlatform()) {// Use the center of the lower half sphere of the capsule as reference point.// This works best when the character is standing on moving tilting platforms. movingPlatform.activeGlobalPoint = tr.position + Vector3.up * (controller.center.y - controller.height*0.5 + controller.radius);movingPlatform.activeLocalPoint = movingPlatform.activePlatform.InverseTransformPoint(movingPlatform.activeGlobalPoint);// Support moving platform rotation as well:
movingPlatform.activeGlobalRotation = tr.
movingPlatform.activeLocalRotation = Quaternion.Inverse(movingPlatform.activePlatform.rotation) * movingPlatform.activeGlobalR }}function FixedUpdate () {if (movingPlatform.enabled) {if (movingPlatform.activePlatform != null) {if (!movingPlatform.newPlatform) {var lastVelocity : Vector3 = movingPlatform.platformVmovingPlatform.platformVelocity = (movingPlatform.activePlatform.localToWorldMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint)- movingPlatform.lastMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint)) / Time.deltaT}movingPlatform.lastMatrix = movingPlatform.activePlatform.localToWorldMmovingPlatform.newPlatform =}else {movingPlatform.platformVelocity = Vector3.}}if (useFixedUpdate)UpdateFunction();}function Update () {if (!useFixedUpdate)UpdateFunction();}private function ApplyInputVelocityChange (velocity : Vector3) {if (!canControl)inputMoveDirection = Vector3.// Find desired velocityvar desiredVelocity : Vector3;if (grounded && TooSteep()) {// The direction we're sliding indesiredVelocity = Vector3(groundNormal.x, 0, groundNormal.z).// Find the input movement direction projected onto the sliding directionvar projectedMoveDir = Vector3.Project(inputMoveDirection, desiredVelocity);// Add the sliding direction, the spped control, and the sideways control vectorsdesiredVelocity = desiredVelocity + projectedMoveDir * sliding.speedControl + (inputMoveDirection - projectedMoveDir) * sliding.sidewaysC// Multiply with the sliding speeddesiredVelocity *= sliding.slidingS}elsedesiredVelocity = GetDesiredHorizontalVelocity();if (movingPlatform.enabled && movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) {desiredVelocity += movement.frameVdesiredVelocity.y = 0;}if (grounded)desiredVelocity = AdjustGroundVelocityToNormal(desiredVelocity, groundNormal);elsevelocity.y = 0;// Enforce max velocity changevar maxVelocityChange : float = GetMaxAcceleration(grounded) * Time.deltaTvar velocityChangeVector : Vector3 = (desiredVelocity - velocity);if (velocityChangeVector.sqrMagnitude & maxVelocityChange * maxVelocityChange) {velocityChangeVector = velocityChangeVector.normalized * maxVelocityC}// If we're in the air and don't have control, don't apply any velocity change at all.// If we're on the ground and don't have control we do apply it - it will correspond to friction.if (grounded || canControl)velocity += velocityChangeVif (grounded) {// When going uphill, the CharacterController will automatically move up by the needed amount.// Not moving it upwards manually prevent risk of lifting off from the ground.// When going downhill, DO move down manually, as gravity is not enough on steep hills.velocity.y = Mathf.Min(velocity.y, 0);}}private function ApplyGravityAndJumping (velocity : Vector3) {if (!inputJump || !canControl) {jumping.holdingJumpButton =jumping.lastButtonDownTime = -100;}if (inputJump && jumping.lastButtonDownTime & 0 && canControl)jumping.lastButtonDownTime = Time.if (grounded)velocity.y = Mathf.Min(0, velocity.y) - movement.gravity * Time.deltaTelse {velocity.y = movement.velocity.y - movement.gravity * Time.deltaT// When jumping up we don't apply gravity for some time when the user is holding the jump button.// This gives more control over jump height by pressing the button longer.if (jumping.jumping && jumping.holdingJumpButton) {// Calculate the duration that the extra jump force should have effect.// If we're still less than that duration after the jumping time, apply the force.if (Time.time & jumping.lastStartTime + jumping.extraHeight / CalculateJumpVerticalSpeed(jumping.baseHeight)) {// Negate the gravity we just applied, except we push in jumpDir rather than jump upwards.velocity += jumping.jumpDir * movement.gravity * Time.deltaT}}// Make sure we don't fall any faster than maxFallSpeed. This gives our character a terminal velocity.velocity.y = Mathf.Max (velocity.y, -movement.maxFallSpeed);}if (grounded) {// Jump only if the jump button was pressed down in the last 0.2 seconds.// We use this check instead of checking if it's pressed down right now// because players will often try to jump in the exact moment when hitting the ground after a jump// and if they hit the button a fraction of a second too soon and no new jump happens as a consequence,// it's confusing and it feels like the game is buggy.if (jumping.enabled && canControl && (Time.time - jumping.lastButtonDownTime & 0.2)) {grounded =jumping.jumping =jumping.lastStartTime = Time.jumping.lastButtonDownTime = -100;jumping.holdingJumpButton =// Calculate the jumping directionif (TooSteep())jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.steepPerpAmount);elsejumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.perpAmount);// Apply the jumping force to the velocity. Cancel any vertical velocity first.velocity.y = 0;velocity += jumping.jumpDir * CalculateJumpVerticalSpeed (jumping.baseHeight);// Apply inertia from platformif (movingPlatform.enabled &&(movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer ||movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)) {movement.frameVelocity = movingPlatform.platformVvelocity += movingPlatform.platformV}SendMessage(&OnJump&, SendMessageOptions.DontRequireReceiver);}else {jumping.holdingJumpButton =}}}function OnControllerColliderHit (hit : ControllerColliderHit) {if (hit.normal.y & 0 && hit.normal.y & groundNormal.y && hit.moveDirection.y & 0) {if ((hit.point - movement.lastHitPoint).sqrMagnitude & 0.001 || lastGroundNormal == Vector3.zero)groundNormal = hit.elsegroundNormal = lastGroundNmovingPlatform.hitPlatform = hit.collider.movement.hitPoint = hit.movement.frameVelocity = Vector3.}}private function SubtractNewPlatformVelocity () {// When landing, subtract the velocity of the new ground from the character's velocity// since movement in ground is relative to the movement of the ground.if (movingPlatform.enabled &&(movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer ||movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)) {// If we landed on a new platform, we have to wait for two FixedUpdates// before we know the velocity of the platform under the characterif (movingPlatform.newPlatform) {var platform : Transform = movingPlatform.activePyield WaitForFixedUpdate();yield WaitForFixedUpdate();if (grounded && platform == movingPlatform.activePlatform)yield 1;}movement.velocity -= movingPlatform.platformV}}private function MoveWithPlatform () : boolean {return (movingPlatform.enabled&& (grounded || movingPlatform.movementTransfer == MovementTransferOnJump.PermaLocked)&& movingPlatform.activePlatform != null);}private function GetDesiredHorizontalVelocity () {// Find desired velocityvar desiredLocalDirection : Vector3 = tr.InverseTransformDirection(inputMoveDirection);var maxSpeed : float = MaxSpeedInDirection(desiredLocalDirection);if (grounded) {// Modify max speed on slopes based on slope speed multiplier curvevar movementSlopeAngle = Mathf.Asin(movement.velocity.normalized.y)
* Mathf.Rad2DmaxSpeed *= movement.slopeSpeedMultiplier.Evaluate(movementSlopeAngle);}return tr.TransformDirection(desiredLocalDirection * maxSpeed);}private function AdjustGroundVelocityToNormal (hVelocity : Vector3, groundNormal : Vector3) : Vector3 {var sideways : Vector3 = Vector3.Cross(Vector3.up, hVelocity);return Vector3.Cross(sideways, groundNormal).normalized * hVelocity.}private function IsGroundedTest () {return (groundNormal.y & 0.01);}function GetMaxAcceleration (grounded : boolean) : float {// Maximum acceleration on ground and in airif (grounded)return movement.maxGroundAelsereturn movement.maxAirA}function CalculateJumpVerticalSpeed (targetJumpHeight : float) {// From the jump height and gravity we deduce the upwards speed // for the character to reach at the apex.return Mathf.Sqrt (2 * targetJumpHeight * movement.gravity);}function IsJumping () {return jumping.}function IsSliding () {return (grounded && sliding.enabled && TooSteep());}function IsTouchingCeiling () {return (movement.collisionFlags & CollisionFlags.CollidedAbove) != 0;}function IsGrounded () {}function TooSteep () {return (groundNormal.y &= Mathf.Cos(controller.slopeLimit * Mathf.Deg2Rad));}function GetDirection () {return inputMoveD}function SetControllable (controllable : boolean) {canControl =}// Project a direction onto elliptical quater segments based on forward, sideways, and backwards speed.// The function returns the length of the resulting vector.function MaxSpeedInDirection (desiredMovementDirection : Vector3) : float {if (desiredMovementDirection == Vector3.zero)return 0;else {var zAxisEllipseMultiplier : float = (desiredMovementDirection.z & 0 ? movement.maxForwardSpeed : movement.maxBackwardsSpeed) / movement.maxSidewaysSvar temp : Vector3 = new Vector3(desiredMovementDirection.x, 0, desiredMovementDirection.z / zAxisEllipseMultiplier).var length : float = new Vector3(temp.x, 0, temp.z * zAxisEllipseMultiplier).magnitude * movement.maxSidewaysS}}function SetVelocity (velocity : Vector3) {grounded =movement.velocity =movement.frameVelocity = Vector3.SendMessage(&OnExternalVelocity&);}// Require a character controller to be attached to the same game object
RequireComponent (CharacterController)@script AddComponentMenu (&Character/Character Motor&)
来火星时代学习unity,强大美术资源,多年游戏教学实力,20000家合作企业,毕业=就业,火星时代unity,业界精英一对一辅导,参与游戏实训项目,工作经验不再是零.
代码有些不懂
这么长代码,一般注释,,,Unity技术&美术交流群,
自己写一个吧,几行代码就行了
登录百度帐号推荐应用
为兴趣而生,贴吧更懂你。或}

我要回帖

更多关于 unity collider2d 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信