当前位置:文档之家› unity3d脚本的常用代码

unity3d脚本的常用代码

隐藏显示对话框
var doWindow0 : boolean = true;

// Make the contents of the window.
//创建窗口的内容。
function DoWindow0 (windowID : int) {
GUI.Button(Rect (10,30, 80,20), "Click Me!");
}

function OnGUI () {
// Make a toggle button for hiding and showing the window
//创建开关按钮,用于隐藏显示窗口
doWindow0 = GUI.Toggle(Rect (10,10,100,20), doWindow0, "Window 0");

// Make sure we only call GUI.Window if doWindow0 is true.
//确定我们如果doWindow0为True,仅调用窗口GUI.Window
if (doWindow0)
GUI.Window(0, Rect(110,10,200,60), DoWindow0, "Basic Window");
}







单击物体,弹出窗口
#pragma strict
static var WindowSwitch :boolean = false;

var windowRect = Rect (200, 80, 240, 100);
function Start () {

}

function Update () {

}
function OnGUI () {
if(WindowSwitch == true) {

windowRect = GUI.Window (0, windowRect, WindowContain, "测试视窗");
}
}function WindowContain (windowID : int){
if (GUI.Button (Rect (70,40,100,20), "关闭视窗")) {
WindowSwitch = false;
}
}
function OnMouseEnter () {
renderer.material.color = Color.red;
}


function OnMouseDown (){
WindowSwitch =true;
}
function OnMouseExit (){
renderer.material.color = Color.white;
}


点击物体,弹出选择框,选择正确则打开新的窗口,否则不响应。

#pragma strict
var aTexture0 : Texture2D;
var aTexture1 : Texture2D;
var aTexture2 : Texture2D;
var aTexture3 : Texture2D;
var aTexture4 : Texture2D;
var aTexture5 : Texture2D;
var aTexture6 : Texture2D;
var aTexture7 : Texture2D;
var aTexture8 : Texture2D;
var aTexture9 : Texture2D;
var aTexture10 : Texture2D;
var aTexture11 : Texture2D;
var aTexture12 : Texture2D;
var aTexture13 : Texture2D;
var aTexture14 : Texture2D;
var aTexture15 : Texture2D;
var aTexture16 : Texture2D;
var aTexture17 : Texture2D;
var aTexture18 : Texture2D;
var aTexture19 : Texture2D;
var aTexture20 : Texture2D;
var aTexture21 : Texture2D;
var aTexture22 : Texture2D;
var aTexture23 : Texture2D;
var aTexture24 : Texture2D;
static var WindowSwitch :boolean = false;
static var WindowSwitch0 :boolean = false;
static var WindowSwitch1 :boolean = false;
static var WindowSwitch2 :boolean = false;
static var WindowSwitch3 :boolean = false;
static var WindowSwitch4 :boolean = false;
static var WindowSwitch5 :boolean = false;
private var toggleImg0 : boolean = false;
private var toggleImg1 : boolean = false;
private var toggleImg2 : boolean = false;
private var toggleImg3 : boolean = false;
private var toggleImg4 : boolean = false;
private var toggleImg5 : boolean = false;
private var toggleImg6 : boolean = false;
private var toggleImg7 : boolean = false;
private var toggleImg8 : boolean = false;
private var toggleImg9 : boolean = false;
private var toggleImg10 : boolean = false;
private var toggleImg11 : boolean = false;
private var toggl

eImg12 : boolean = false;
private var toggleImg13 : boolean = false;
private var toggleImg14 : boolean = false;
private var toggleImg15 : boolean = false;
private var toggleImg16 : boolean = false;
private var toggleImg17 : boolean = false;
private var toggleImg18 : boolean = false;
private var toggleImg19 : boolean = false;
private var toggleImg20 : boolean = false;
var windowRect = Rect (200, 80,400,80);
var windowRect0 = Rect (200, 80,400,80);
var windowRect1 = Rect (200, 80, 400,80);
var windowRect2 = Rect (200, 80, 400,80);
var windowRect3 = Rect (200, 80,400,80);
var windowRect4 = Rect (200, 80, 400,80);
var windowRect5 = Rect (200, 80, 400,80);

function Start () {

}

function Update () {

}


function OnGUI () {


if(WindowSwitch0 == true) {

windowRect0 = GUI.Window (0, windowRect0, WindowContain0, ".");

}

else if(WindowSwitch1 == true) {

windowRect1 = GUI.Window (0, windowRect1, WindowContain1, "题1");
}
else if(WindowSwitch2 == true) {

windowRect2 = GUI.Window (0, windowRect2, WindowContain2, "题2");
} else if(WindowSwitch3 == true) {

windowRect3 = GUI.Window (0, windowRect3, WindowContain3, "题3");
}else if(WindowSwitch4 == true) {

windowRect4 = GUI.Window (0, windowRect4, WindowContain4, "题4");
}else if(WindowSwitch5 == true) {

windowRect5 = GUI.Window (0, windowRect5, WindowContain5, "正确");
}


}


function WindowContain0 (windowID : int)
{
https://www.doczj.com/doc/295696192.html,bel(Rect(10, 10, 500, 150),aTexture0);
if(GUI.Toggle(Rect(10, 60, 150,80 ), toggleImg0, "yes"))
{
WindowSwitch0=false;
WindowSwitch1=true;
Debug.Log("1000");
}
else if(GUI.Toggle(Rect(170, 60, 150, 80), toggleImg1, "no"))
{WindowSwitch0=false;
Debug.Log("2000");}

}



function WindowContain1 (windowID : int)
{
https://www.doczj.com/doc/295696192.html,bel(Rect(10, 10, 500, 150),aTexture1);
if(GUI.Toggle(Rect(10, 70, 100, 30), toggleImg2, aTexture2))
{

Debug.Log("1000");
}
else if(GUI.Toggle(Rect(120, 70, 100, 30), toggleImg3, aTexture3))
{Debug.Log("2000");}
else if(GUI.Toggle(Rect(230, 70, 100, 30), toggleImg4, aTexture4))
{ WindowSwitch1=false;
WindowSwitch2=true;
Debug.Log("2000");}
else if(GUI.Toggle(Rect(340, 70, 100, 30), toggleImg5, aTexture5))
{Debug.Log("2000");}
}




function WindowContain2 (windowID : int)
{
https://www.doczj.com/doc/295696192.html,bel(Rect(10, 10, 500, 150),aTexture6);
if(GUI.Toggle(Rect(10, 70, 100, 30), toggleImg6, aTexture7))
{

Debug.Log("1000");
}
else if(GUI.Toggle(Rect(120, 70, 100, 30), toggleImg7, aTexture8))
{Debug.Log("2000");}
else if(GUI.Toggle(Rect(230, 70, 100, 30), toggleImg8, aTexture9))
{
Debug.Log("2000");}
else if(GUI.Toggle(Rect(340, 70, 100, 30), toggleImg9, aTexture10))
{WindowSwitch2=false;
WindowSwitch3=true;
Debug.Log("2000");}
}


function WindowContain3 (windowID : int)
{

https://www.doczj.com/doc/295696192.html,bel(Rect(10, 10, 500, 150),aTexture11);
if(GUI.Toggle(Rect(10, 70, 100, 30), toggleImg10, aTexture12))
{ WindowSwitch3=false;
WindowSwitch4=true;
Debug.Log("1000");
}
else if(GUI.Toggle(Rect(120, 70, 100, 30), toggleImg11, aTexture13))
{Debug.Log("2000");}
else if(GUI.Toggle(Rect(230, 70, 100, 30), toggleImg12, aTexture14))
{
Debug.Log("2000");}
else if(GUI.Toggle(Rect(340, 70, 100, 30), toggleImg13, aTexture15))
{
Debug.Log("2000");}
}

function WindowContain4 (windowID : int)
{
https://www.doczj.com/doc/295696192.html,bel(Rect(10, 10, 500, 150),aTexture16);
if(GUI.Toggle(Rect(10, 70, 100, 30), toggleImg14, aTexture17))
{ WindowSwitch4=false;
WindowSwitch5=true;
Debug.Log("1000");
}
else if(GUI.Toggle(Rect(120, 70, 100, 30), toggleImg15, aTexture18))
{Debug.Log("2000");}
else if(GUI.Toggle(Rect(230, 70, 100, 30), toggleImg16, aTexture19))
{
Debug.Log("2000");}
else if(GUI.Toggle(Rect(340, 70, 100, 30), toggleImg17, aTexture20))
{
Debug.Log("2000");}
}


function WindowContain5 (windowID : int)
{
https://www.doczj.com/doc/295696192.html,bel(Rect(10, 10, 500, 150),aTexture21);
if(GUI.Button(Rect(10, 60, 80, 20),"yes"))
{

WindowSwitch5=false;
transform.Translate(Vector3(80,0,0));
Debug.Log("3000");

}
else if(GUI.Button(Rect(120, 60, 80, 20), "no"))
{
WindowSwitch5=false;
Debug.Log("2000");
}
}


function OnMouseEnter () {
renderer.material.color = Color.red;
}


function OnMouseDown (){
WindowSwitch0=true;
}
function OnMouseExit (){
renderer.material.color = Color.white;
}





















在按钮上显示图片,单击按钮时,切换场景
#pragma strict
var image:Texture2D;
function Start () {

}

function Update () {

}
function OnGUI(){

if (GUI.Button(Rect(800,190,200,50),image))
{
Application.LoadLevel(1);
}


}








摄像机控制 带缓冲的镜头拉近效果
#pragma strict
var target : Transform;
var distance : float = 3.0;
var height : float = 1.0;
var damping : float = 5.0;
var smoothRotation : boolean = true;
var rotationDamping : float = 10.0;

var targetLookAtOffset : Vector3; // allows offsetting of camera lookAt, very useful for low bumper heights

var bumperDistanceCheck : float = 2.5; // length of bumper ray
var bumperCameraHeight : float = 1.0; // adjust camera height while bumping
var bumperRayOffset : Vector3; // allows offset of the bumper ray from target origin

function Start () {

}

function Update () {

}
function FixedUpdate() {

var wantedPosition = target.TransformPoint(0, height, -distance);

// check to see if there is anything behind the target
var hit : RaycastHit;
var back = target.transform.TransformDirection(-1 * Vector3.forward);

// cast the bumper ray out from rear and check to see if there is anything behind
if (Physics.Raycast(target.TransformPoint(bumperRayOffset

), back, hit, bumperDistanceCheck)) {
// clamp wanted position to hit position
wantedPosition.x = hit.point.x;
wantedPosition.z = hit.point.z;
wantedPosition.y = Mathf.Lerp(hit.point.y + bumperCameraHeight, wantedPosition.y, Time.deltaTime * damping);
}

transform.position = Vector3.Lerp(transform.position, wantedPosition, Time.deltaTime * damping);

var lookPosition : Vector3 = target.TransformPoint(targetLookAtOffset);

if (smoothRotation) {
var wantedRotation : Quaternion = Quaternion.LookRotation(lookPosition - transform.position, target.up);
transform.rotation = Quaternion.Slerp(transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
} else {
transform.rotation = Quaternion.LookRotation(lookPosition - transform.position, target.up);
}
}










第三人键盘控制:
// Require a character controller to be attached to the same game object
@script RequireComponent(CharacterController)

public var idleAnimation : AnimationClip;
public var walkAnimation : AnimationClip;
public var runAnimation : AnimationClip;
public var jumpPoseAnimation : AnimationClip;

public var walkMaxAnimationSpeed : float = 0.75;
public var trotMaxAnimationSpeed : float = 1.0;
public var runMaxAnimationSpeed : float = 1.0;
public var jumpAnimationSpeed : float = 1.15;
public var landAnimationSpeed : float = 1.0;

private var _animation : Animation;

enum CharacterState {
Idle = 0,
Walking = 1,
Trotting = 2,
Running = 3,
Jumping = 4,
}

private var _characterState : CharacterState;

// The speed when walking
var walkSpeed = 2.0;
// after trotAfterSeconds of walking we trot with trotSpeed
var trotSpeed = 4.0;
// when pressing "Fire3" button (cmd) we start running
var runSpeed = 6.0;

var inAirControlAcceleration = 3.0;

// How high do we jump when pressing jump and letting go immediately
var jumpHeight = 0.5;

// The gravity for the character
var gravity = 20.0;
// The gravity in controlled descent mode
var speedSmoothing = 10.0;
var rotateSpeed = 500.0;
var trotAfterSeconds = 3.0;

var canJump = true;

private var jumpRepeatTime = 0.05;
private var jumpTimeout = 0.15;
private var groundedTimeout = 0.25;

// The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.
private var lockCameraTimer = 0.0;

// The current move direction in x-z
private var moveDirection = Vector3.zero;
// The current vertical speed
private var verticalSpeed = 0.0;
// The current x-z move speed
private var moveSpeed = 0.0;

// The last collision flags returned from controller.Move
private var collisionFlags : CollisionFlags;

// Are we jumping? (Initiated with jump button and not grounded yet)
private var jumping = false;
private var jumpingReachedApex = false;

// Are we moving backwards (This locks the camera to not do a 180 degree spin)
private var movingBack = false;
// Is the user pressing any keys?
private va

r isMoving = false;
// When did the user start walking (Used for going into trot after a while)
private var walkTimeStart = 0.0;
// Last time the jump button was clicked down
private var lastJumpButtonTime = -10.0;
// Last time we performed a jump
private var lastJumpTime = -1.0;


// the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
private var lastJumpStartHeight = 0.0;


private var inAirVelocity = Vector3.zero;

private var lastGroundedTime = 0.0;


private var isControllable = true;

function Awake ()
{
moveDirection = transform.TransformDirection(Vector3.forward);

_animation = GetComponent(Animation);
if(!_animation)
Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");

/*
public var idleAnimation : AnimationClip;
public var walkAnimation : AnimationClip;
public var runAnimation : AnimationClip;
public var jumpPoseAnimation : AnimationClip;
*/
if(!idleAnimation) {
_animation = null;
Debug.Log("No idle animation found. Turning off animations.");
}
if(!walkAnimation) {
_animation = null;
Debug.Log("No walk animation found. Turning off animations.");
}
if(!runAnimation) {
_animation = null;
Debug.Log("No run animation found. Turning off animations.");
}
if(!jumpPoseAnimation && canJump) {
_animation = null;
Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations.");
}

}


function UpdateSmoothedMovementDirection ()
{
var cameraTransform = Camera.main.transform;
var grounded = IsGrounded();

// Forward vector relative to the camera along the x-z plane
var forward = cameraTransform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;

// Right vector relative to the camera
// Always orthogonal to the forward vector
var right = Vector3(forward.z, 0, -forward.x);

var v = Input.GetAxisRaw("Vertical");
var h = Input.GetAxisRaw("Horizontal");

// Are we moving backwards or looking backwards
if (v < -0.2)
movingBack = true;
else
movingBack = false;

var wasMoving = isMoving;
isMoving = Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1;

// Target direction relative to the camera
var targetDirection = h * right + v * forward;

// Grounded controls
if (grounded)
{
// Lock camera for short period when transitioning moving & standing still
lockCameraTimer += Time.deltaTime;
if (isMoving != wasMoving)
lockCameraTimer = 0.0;

// We store speed and direction seperately,
// so that when the character stands still we still have a valid forward direction
// moveDirection is always normalized, and we only update it if there is user input.
if (targetDirection != Vector3.zero)
{
// If we are really slow, just snap to the target direction
if (moveSpeed < walkSpeed * 0.9 && grounded)
{
moveDirection = t

argetDirection.normalized;
}
// Otherwise smoothly turn towards it
else
{
moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);

moveDirection = moveDirection.normalized;
}
}

// Smooth the speed based on the current target direction
var curSmooth = speedSmoothing * Time.deltaTime;

// Choose target speed
//* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
var targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0);

_characterState = CharacterState.Idle;

// Pick speed modifier
if (Input.GetKey (KeyCode.LeftShift) | Input.GetKey (KeyCode.RightShift))
{
targetSpeed *= runSpeed;
_characterState = CharacterState.Running;
}
else if (Time.time - trotAfterSeconds > walkTimeStart)
{
targetSpeed *= trotSpeed;
_characterState = CharacterState.Trotting;
}
else
{
targetSpeed *= walkSpeed;
_characterState = CharacterState.Walking;
}

moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);

// Reset walk time start when we slow down
if (moveSpeed < walkSpeed * 0.3)
walkTimeStart = Time.time;
}
// In air controls
else
{
// Lock camera while in air
if (jumping)
lockCameraTimer = 0.0;

if (isMoving)
inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;
}



}


function ApplyJumping ()
{
// Prevent jumping too fast after each other
if (lastJumpTime + jumpRepeatTime > Time.time)
return;

if (IsGrounded()) {
// Jump
// - Only when pressing the button down
// - With a timeout so you can press the button slightly before landing
if (canJump && Time.time < lastJumpButtonTime + jumpTimeout) {
verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight);
SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
}
}
}


function ApplyGravity ()
{
if (isControllable) // don't move player at all if not controllable.
{
// Apply gravity
var jumpButton = Input.GetButton("Jump");


// When we reach the apex of the jump we send out a message
if (jumping && !jumpingReachedApex && verticalSpeed <= 0.0)
{
jumpingReachedApex = true;
SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
}

if (IsGrounded ())
verticalSpeed = 0.0;
else
verticalSpeed -= gravity * Time.deltaTime;
}
}

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 * gravity);
}

function DidJump ()
{
jumping = true;
jumpingReachedApex = false;
lastJumpTime = Time.time;
lastJumpStartHeight = transform.position.y;
lastJumpButtonTime = -10;

_characterState = CharacterState.Jumpi

ng;
}

function Update() {

if (!isControllable)
{
// kill all inputs if not controllable.
Input.ResetInputAxes();
}

if (Input.GetButtonDown ("Jump"))
{
lastJumpButtonTime = Time.time;
}

UpdateSmoothedMovementDirection();

// Apply gravity
// - extra power jump modifies gravity
// - controlledDescent mode modifies gravity
ApplyGravity ();

// Apply jumping logic
ApplyJumping ();

// Calculate actual motion
var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity;
movement *= Time.deltaTime;

// Move the controller
var controller : CharacterController = GetComponent(CharacterController);
collisionFlags = controller.Move(movement);

// ANIMATION sector
if(_animation) {
if(_characterState == CharacterState.Jumping)
{
if(!jumpingReachedApex) {
_animation[https://www.doczj.com/doc/295696192.html,].speed = jumpAnimationSpeed;
_animation[https://www.doczj.com/doc/295696192.html,].wrapMode = WrapMode.ClampForever;
_animation.CrossFade(https://www.doczj.com/doc/295696192.html,);
} else {
_animation[https://www.doczj.com/doc/295696192.html,].speed = -landAnimationSpeed;
_animation[https://www.doczj.com/doc/295696192.html,].wrapMode = WrapMode.ClampForever;
_animation.CrossFade(https://www.doczj.com/doc/295696192.html,);
}
}
else
{
if(controller.velocity.sqrMagnitude < 0.1) {
_animation.CrossFade(https://www.doczj.com/doc/295696192.html,);
}
else
{
if(_characterState == CharacterState.Running) {
_animation[https://www.doczj.com/doc/295696192.html,].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, runMaxAnimationSpeed);
_animation.CrossFade(https://www.doczj.com/doc/295696192.html,);
}
else if(_characterState == CharacterState.Trotting) {
_animation[https://www.doczj.com/doc/295696192.html,].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, trotMaxAnimationSpeed);
_animation.CrossFade(https://www.doczj.com/doc/295696192.html,);
}
else if(_characterState == CharacterState.Walking) {
_animation[https://www.doczj.com/doc/295696192.html,].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, walkMaxAnimationSpeed);
_animation.CrossFade(https://www.doczj.com/doc/295696192.html,);
}

}
}
}
// ANIMATION sector

// Set rotation to the move direction
if (IsGrounded())
{

transform.rotation = Quaternion.LookRotation(moveDirection);

}
else
{
var xzMove = movement;
xzMove.y = 0;
if (xzMove.sqrMagnitude > 0.001)
{
transform.rotation = Quaternion.LookRotation(xzMove);
}
}

// We are in jump mode but just became grounded
if (IsGrounded())
{
lastGroundedTime = Time.time;
inAirVelocity = Vector3.zero;
if (jumping)
{
jumping = false;
SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
}
}
}

function OnControllerColliderHit (hit : ControllerColliderHit )
{
// Debug.DrawRay(hit.point, hit.normal);
if (hit.moveDirection.y > 0.01)
return;
}

function GetSpeed () {
return moveSpeed;
}

function IsJumping () {
return jumping;
}

function IsGrounded () {

return (collisionFlags & CollisionFlags.CollidedBelow) != 0;
}

function GetDirection () {
return moveDirection;
}

function IsMovingBackwards () {
return movingBack;
}

function GetLockCameraTimer ()
{
return lockCameraTimer;
}

function IsMoving () : boolean
{
return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5;
}

function HasJumpReachedApex ()
{
return jumpingReachedApex;
}

function IsGroundedWithTimeout ()
{
return lastGroundedTime + groundedTimeout > Time.time;
}

function Reset ()
{
gameObject.tag = "Player";
}








第三人视角控制:


var cameraTransform : Transform;
private var _target : Transform;

// The distance in the x-z plane to the target

var distance = 7.0;

// the height we want the camera to be above the target
var height = 3.0;

var angularSmoothLag = 0.3;
var angularMaxSpeed = 15.0;

var heightSmoothLag = 0.3;

var snapSmoothLag = 0.2;
var snapMaxSpeed = 720.0;

var clampHeadPositionScreenSpace = 0.75;

var lockCameraTimeout = 0.2;

private var headOffset = Vector3.zero;
private var centerOffset = Vector3.zero;

private var heightVelocity = 0.0;
private var angleVelocity = 0.0;
private var snap = false;
private var controller : ThirdPersonController;
private var targetHeight = 100000.0;

function Awake ()
{
if(!cameraTransform && Camera.main)
cameraTransform = Camera.main.transform;
if(!cameraTransform) {
Debug.Log("Please assign a camera to the ThirdPersonCamera script.");
enabled = false;
}


_target = transform;
if (_target)
{
controller = _target.GetComponent(ThirdPersonController);
}

if (controller)
{
var characterController : CharacterController = _target.collider;
centerOffset = characterController.bounds.center - _target.position;
headOffset = centerOffset;
headOffset.y = characterController.bounds.max.y - _target.position.y;
}
else
Debug.Log("Please assign a target to the camera that has a ThirdPersonController script attached.");


Cut(_target, centerOffset);
}

function DebugDrawStuff ()
{
Debug.DrawLine(_target.position, _target.position + headOffset);

}

function AngleDistance (a : float, b : float)
{
a = Mathf.Repeat(a, 360);
b = Mathf.Repeat(b, 360);

return Mathf.Abs(b - a);
}

function Apply (dummyTarget : Transform, dummyCenter : Vector3)
{
// Early out if we don't have a target
if (!controller)
return;

var targetCenter = _target.position + centerOffset;
var targetHead = _target.position + headOffset;

// DebugDrawStuff();

// Calculate the current & target rotation angles
var originalTargetAngle = _target.eulerAngles.y;
var currentAngle = cameraTransform.eulerAngles.y;

// Adjust real target angle when camera is locked
var targetAngle = originalTargetAngle;

// When pressing Fire2 (alt) the camera will snap to the target direction real quick.

// It will stop snapping when it reaches the target
if (Input.GetButton("Fire2"))
snap = true;

if (snap)
{
// We are close to the target, so we can stop snapping now!
if (AngleDistance (currentAngle, originalTargetAngle) < 3.0)
snap = false;

currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, snapSmoothLag, snapMaxSpeed);
}
// Normal camera motion
else
{
if (controller.GetLockCameraTimer () < lockCameraTimeout)
{
targetAngle = currentAngle;
}

// Lock the camera when moving backwards!
// * It is really confusing to do 180 degree spins when turning around.
if (AngleDistance (currentAngle, targetAngle) > 160 && controller.IsMovingBackwards ())
targetAngle += 180;

currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, angularSmoothLag, angularMaxSpeed);
}


// When jumping don't move camera upwards but only down!
if (controller.IsJumping ())
{
// We'd be moving the camera upwards, do that only if it's really high
var newTargetHeight = targetCenter.y + height;
if (newTargetHeight < targetHeight || newTargetHeight - targetHeight > 5)
targetHeight = targetCenter.y + height;
}
// When walking always update the target height
else
{
targetHeight = targetCenter.y + height;
}

// Damp the height
var currentHeight = cameraTransform.position.y;
currentHeight = Mathf.SmoothDamp (currentHeight, targetHeight, heightVelocity, heightSmoothLag);

// Convert the angle into a rotation, by which we then reposition the camera
var currentRotation = Quaternion.Euler (0, currentAngle, 0);

// Set the position of the camera on the x-z plane to:
// distance meters behind the target
cameraTransform.position = targetCenter;
cameraTransform.position += currentRotation * Vector3.back * distance;

// Set the height of the camera
cameraTransform.position.y = currentHeight;

// Always look at the target
SetUpRotation(targetCenter, targetHead);
}

function LateUpdate () {
Apply (transform, Vector3.zero);
}

function Cut (dummyTarget : Transform, dummyCenter : Vector3)
{
var oldHeightSmooth = heightSmoothLag;
var oldSnapMaxSpeed = snapMaxSpeed;
var oldSnapSmooth = snapSmoothLag;

snapMaxSpeed = 10000;
snapSmoothLag = 0.001;
heightSmoothLag = 0.001;

snap = true;
Apply (transform, Vector3.zero);

heightSmoothLag = oldHeightSmooth;
snapMaxSpeed = oldSnapMaxSpeed;
snapSmoothLag = oldSnapSmooth;
}

function SetUpRotation (centerPos : Vector3, headPos : Vector3)
{
// Now it's getting hairy. The devil is in the details here, the big issue is jumping of course.
// * When jumping up and down we don't want to center the guy in screen space.
// This is important to give a feel for how high you jump and avoiding large camera movements.
//
// * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth.
//


// So here is what we will do:
//
// 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis
// 2. When grounded we make him be centered
// 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold
// 4. When landing we smoothly interpolate towards centering him on screen
var cameraPos = cameraTransform.position;
var offsetToCenter = centerPos - cameraPos;

// Generate base rotation only around y-axis
var yRotation = Quaternion.LookRotation(Vector3(offsetToCenter.x, 0, offsetToCenter.z));

var relativeOffset = Vector3.forward * distance + Vector3.down * height;
cameraTransform.rotation = yRotation * Quaternion.LookRotation(relativeOffset);

// Calculate the projected center position and top position in world space
var centerRay = cameraTransform.camera.ViewportPointToRay(Vector3(.5, 0.5, 1));
var topRay = cameraTransform.camera.ViewportPointToRay(Vector3(.5, clampHeadPositionScreenSpace, 1));

var centerRayPos = centerRay.GetPoint(distance);
var topRayPos = topRay.GetPoint(distance);

var centerToTopAngle = Vector3.Angle(centerRay.direction, topRay.direction);

var heightToAngle = centerToTopAngle / (centerRayPos.y - topRayPos.y);

var extraLookAngle = heightToAngle * (centerRayPos.y - centerPos.y);
if (extraLookAngle < centerToTopAngle)
{
extraLookAngle = 0;
}
else
{
extraLookAngle = extraLookAngle - centerToTopAngle;
cameraTransform.rotation *= Quaternion.Euler(-extraLookAngle, 0, 0);
}
}

function GetCenterOffset ()
{
return centerOffset;
}




单击鼠标调整角色视角
void Update ()
{
if(Input.GetMouseButtonDown(0)){




物体旋转
#pragma strict

function Start () {

}

function Update () {
transform.Rotate(0,10*Time.deltaTime,0);
}




隐藏和显示物体
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
public Transform target;
void Start(){
}
void OnGUI(){
//renderer control
if(GUILayout.Button("display")){
MeshRenderer[] marr = target.GetComponentsInChildren(true);
foreach(MeshRenderer m in marr){
m.enabled = true;
}
}
if(GUILayout.Button("hide")){
MeshRenderer[] marr = target.GetComponentsInChildren(true);
foreach(MeshRenderer m in marr){
m.enabled = false;
}
}
}
}

java
void OnGUI()
{
if(GUILayout.Button("显示/隐藏"))
{
if(gameObject.active == false)
{
gameObject.active = true;
}
else
{
gameObject.active = fal

se;
}
}
}


先隐藏后显示
#pragma strict
var wuti0:GameObject;
function Start () {
wuti0.active=false;
}

function Update () {



}
function OnGUI()
{
if(GUILayout.Button("显示/隐藏"))
{
wuti0.active = true;
}

}




摄像机通过按F1-F5键分别追踪五个物体
#pragma strict
var target : Transform;
var distance : float = 3.0;
var po:int=0;
var height : float = 0;
var damping : float = 5.0;
var smoothRotation : boolean = true;
var rotationDamping : float = 10.0;
var mb1:String;

var targetLookAtOffset : Vector3; // allows offsetting of camera lookAt, very useful for low bumper heights

var bumperDistanceCheck : float = 2.5; // length of bumper ray
var bumperCameraHeight : float = 1.0; // adjust camera height while bumping
var bumperRayOffset : Vector3; // allows offset of the bumper ray from target origin

function Start () {

}

function Update () {
if(Input.GetKeyUp(KeyCode.F1))
{
po=1;
}else if(Input.GetKeyUp(KeyCode.F2)){

po=2;

}else if(Input.GetKeyUp(KeyCode.F3)){

po=3;

}else if(Input.GetKeyUp(KeyCode.F4)){

po=4;

}else if(Input.GetKeyUp(KeyCode.F5)){

po=5;

}
if(po==1){

mb1="biao0";
target=GameObject.Find(mb1).transform;
a1();
} else if(po==2){

mb1="biao1";
target=GameObject.Find(mb1).transform;
a1();

}else if(po==3){

mb1="biao2";
target=GameObject.Find(mb1).transform;
a1();
}else if(po==4){

mb1="biao3";
target=GameObject.Find(mb1).transform;
a1();
}else if(po==5){

mb1="biao4";
target=GameObject.Find(mb1).transform;
a1();
}

}




function a1(){


var wantedPosition = target.TransformPoint(0, height, -distance);
// check to see if there is anything behind the target
var hit : RaycastHit;
var back = target.transform.TransformDirection(-1 * Vector3.forward);

// cast the bumper ray out from rear and check to see if there is anything behind
if (Physics.Raycast(target.TransformPoint(bumperRayOffset), back, hit, bumperDistanceCheck)) {
// clamp wanted position to hit position
wantedPosition.x = hit.point.x;
wantedPosition.z = hit.point.z;
wantedPosition.y = Mathf.Lerp(hit.point.y + bumperCameraHeight, wantedPosition.y, Time.deltaTime * damping);
}

transform.position = Vector3.Lerp(transform.position, wantedPosition, Time.deltaTime * damping);

var lookPosition : Vector3 = target.TransformPoint(targetLookAtOffset);

if (smoothRotation) {
var wantedRotation : Quaternion = Quaternion.LookRotation(lookPosition - transform.position, target.up);
transform.rotation = Quaternion.Slerp(transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
} else {
transform.rotation = Quaternion.LookRotation(lookPosition - transform.position, target.up);
}
}





鼠标滚轮控制镜头远近
using UnityEngine;
using System.Collections;

public class near : MonoBehaviour {

public float minFov = 15f;
public float maxFov = 90f;
public

float sensitivity = 10f;

void Update()
{
float fov = Camera.main.fieldOfView;
fov += -Input.GetAxis("Mouse ScrollWheel") * sensitivity;
fov = Mathf.Clamp(fov, minFov, maxFov);
Camera.main.fieldOfView = fov;
}
}



在鼠标点击的位置上绘制一张图片出来(关于绘制GUI界面坐标系与屏幕坐标系之间的关系)。


[csharp] view plaincopy
using UnityEngine;
using System.Collections;
public class test0 : MonoBehaviour {
//图片
public Texture img;
//储存鼠标的位置坐标
private Vector2 pos;
void OnGUI()
{
//鼠标左击,获取当前鼠标的位置
if (Input.GetMouseButton(0))
{
pos = Input.mousePosition;
}
//绘制图片
GUI.DrawTexture(new Rect(pos.x,Screen.height - pos.y,100,100), img);
}
}



坐标显示和坐标转换(这个是触摸方面的。如果没有触摸屏,那就将那个if去掉吧!)




[csharp] view plaincopy
using UnityEngine;
using System.Collections;
public class test: MonoBehaviour {
//场景的相机,拖放进来
public Camera camera;
//场景的物体
private GameObject obj;
void Start()
{
//初始化
obj = GameObject.Find("Plane");
}
void Update ()
{
//有触摸
if (Input.touchCount > 0)
{
print("世界坐标" + obj.transform.position);
print("屏幕坐标" + Input.GetTouch(0).position);
print("世界坐标→屏幕坐标" + camera.WorldToScreenPoint(obj.transform.position));
print("屏幕坐标→视口坐标" + camera.ScreenToViewportPoint(Input.GetTouch(0).position));
print("世界坐标→视口坐标" + camera.WorldToViewportPoint(obj.transform.position));
}
}
}





Unity3D中制作一个GUI对话框界面



#pragma strict
var icons : Texture2D[]; //存放要动态播放的图片,图片尺寸要求2的幂次方
var timeElasped : float = 0; //过去的时间
var fps : float = 0.4f; //两帧间隔时间,想图片播放快一些就把值相应设小。
var curFrame : int = 0; //当前播放帧索引值
var icon : Texture2D; //GUI上某一时刻要显示的图片,从icons数组中获取。
var tex1:String;//说话对象
var tex3:String;//说话内容
var windowRect :

Rect = Rect(300,250,440,200);//对话框的面积大小
var windowOpen:boolean = true;//标识对话框是否显示
var styleB:GUIStyle;//确定按钮的样式
var style:GUIStyle;//对话框窗口的样式
var styleLab1:GUIStyle;//说话对象文字的样式
var styleLab2:GUIStyle;//说话内容文字的样式
function Start () {

}


function OnWindowDraw(winid:int){

if (GUI.Button(Rect(385,172,42,15),"",styleB)){
windowOpen = false;
}

https://www.doczj.com/doc/295696192.html,bel(Rect(140,12,156,20),tex1,styleLab1);
https://www.doczj.com/doc/295696192.html,bel(Rect(16,6,110,179),icon);
GUI.color=Color.white;
https://www.doczj.com/doc/295696192.html,bel(Rect(140,32,256,70),tex3,styleLab2);
GUI.DragWindow();
}

function OnGUI(){
if(windowOpen){
windowRect = GUI.Window(0,windowRect,OnWindowDraw,"",style);
}
}

function Update() {
//累计时间
timeElasped += Time.deltaTime;
if(timeElasped >= fps) {
timeElasped = 0;
curFrame++;
if(curFrame >= icons.Length) {
curFrame = 0;
}
icon = icons[curFrame];
}
}





按下方向键“上”控制角色走,放开角色停
#pragma strict

function Start () {

}

function Update () {
if (Input.GetAxis("Vertical") > 0.2)

animation.CrossFade ("walk");

else

animation.CrossFade ("idle");
}




通过按键控制多个动画的连续播放(视频资料https://www.doczj.com/doc/295696192.html,/thread-120090-1-1.html)
#pragma strict

function Start () {

}

function Update () {
if (Input.GetKey(KeyCode.A))
{

this animation.CrossFade("mode1");
//mode1是指的动画的名称
}
else if (Input.GetKey(KeyCode.S))
(

this animation.CrossFade("mode2");
//mode2是指第二个动画的名称
)


}




直升机飞行控制https://www.doczj.com/doc/295696192.html,/thread-211649-1-1.html

W键:前进
S键:后退
A键:左转弯
D键:右转弯
↑方向键:上升
↓方向键:下降
←方向键:左侧飞
→方向键:右侧飞

using UnityEngine;
using System.Collections;

public class Handler : MonoBehaviour {

public GameObject helicopter;

public GameObject rotor01;
public GameObject rotor02;
public GameObject rotor03;

float curRotX = 0;
float curRotY = 0;
float curRotZ = 0;

// Use this for initialization
void Start ()
{
helicopter = GameObject.Find("Body");

rotor01 = GameObject.Find("Rotor01");
rotor02 = GameObject.Find("Rotor02");
rotor03 = GameObject.Find("Rotor03");
}

// Update is called once per frame
void FixedUpdate ()
{
rotor01.transform.Rotate(new Vector3((float)0, (float)-10, (float)0));
rotor02.transform.Rotate(new Vector3((float)0, (float)-10, (float)0));
rotor03.transform.Rotate(n

ew Vector3((float)10, (float)0, (float)0));

if(Input.GetKey(KeyCode.W))
{
//float angleY = helicopter.transform.RotateAround(new Vector3(1f,0f,0f), 15);

//helicopter.transform.Translate((float)0.0,(float)0.06,(float)0.0);
//helicopter.transform.rotation = Quaternion.Euler(new Vector3((float)15,curRotY,curRotZ));

//helicopter.transform.localRotation = Quaternion.Euler(new Vector3((float)15,curRotY,curRotZ));

helicopter.transform.Translate(Vector3.forward * Time.deltaTime * 5);


//helicopter.transform.Translate((float)0.0,(float)0.0268,(float)0.0);


}
else if(Input.GetKey(KeyCode.A))
{

helicopter.transform.Rotate(new Vector3((float)0, (float)-2, (float)0));

}
else if(Input.GetKey(KeyCode.S))
{
helicopter.transform.Translate(Vector3.forward * Time.deltaTime * -5) ;
}
else if(Input.GetKey(KeyCode.D))
{
helicopter.transform.Rotate(new Vector3((float)0, (float)2, (float)0));

}
else if(Input.GetKey(KeyCode.UpArrow))
{
helicopter.transform.Translate((float)0.0,(float)0.1,(float)0.0);
}
else if(Input.GetKey(KeyCode.DownArrow))
{
helicopter.transform.Translate((float)0.0,(float)-0.1,(float)0.0);
}
else if(Input.GetKey(KeyCode.LeftArrow))
{
helicopter.transform.Translate((float)-0.1,(float)0.0,(float)0.0);
}
else if(Input.GetKey(KeyCode.RightArrow))
{
helicopter.transform.Translate((float)0.1,(float)0.0,(float)0.0);
}

if(Input.GetKeyUp(KeyCode.W))
{

//helicopter.transform.rotation = Quaternion.Euler(new Vector3((float)0.0, this.curRotY, this.curRotZ));

}
}
}






通过点击按钮为墙壁地面更换材质(https://www.doczj.com/doc/295696192.html,/thread-134275-1-1.html)


#pragma strict
public var curObject:GameObject = null;
private var _wall01:GameObject = null;
private var _wall02:GameObject = null;
private var _floor:GameObject = null;
public var _wall01Material:Material = null;
public var _wall02Material:Material = null;
public var _floor01Material:Material = null;
public var _floor02Material:Materia

l = null;
function Start()
{
_wall01 = GameObject.Find("wall01");
_wall02 = GameObject.Find("wall02");
_floor = GameObject.Find("floor");
}
function Update()
{
// 获得当前选中的对象
if (Input.GetMouseButton (0))
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit))
{
Debug.DrawLine (ray.origin, hit.point);
//print(https://www.doczj.com/doc/295696192.html,);

curObject = hit.collider.gameObject;

// 显示当前选中对象的名称
print(curObject);
}

}
}
function OnGUI()
{
// 给选中的墙壁更换墙纸1
if(GUI.Button(Rect(10, 10, 100, 80), "墙纸1"))
{
if(curObject == null)
{
return;
}
// 用户选中的是墙壁
if(curObject == _wall01 || curObject == _wall02)
{
curObject.renderer.material = _wall01Material;
}
}

// 给选中的墙壁更换墙纸2
if(GUI.Button(Rect(120, 10, 100, 80), "墙纸2"))
{
if(curObject == null)
{
return;
}

// 用户选中的是墙壁
if(curObject == _wall01 || curObject == _wall02)
{
curObject.renderer.material = _wall02Material;
}
}

// 给选中的地板更换地板1
if(GUI.Button(Rect(230, 10, 100, 80), "地板1"))
{
if(curObject == null)
{
return;
}

// 用户选中的是地板
if(curObject == _floor)
{
curObject.renderer.material = _floor01Material;
}
}

// 给选中的地板更换地板2
if(GUI.Button(Rect(340, 10, 100, 80), "地板2"))
{
if(curObject == null)
{
return;
}

// 用户选中的是地板
if(curObject == _floor)
{
curObject.renderer.material = _floor02Material;
}
}
}



全屏播放视频(脚本绑定到摄像机,并删除其他所有东西)


using UnityEngine;
using System.Collections;

public class Test: MonoBehaviour
{

//电影纹理
public MovieTexture movTexture;

void Start()
{
//设置电影纹理播放模式为循环
movTexture.loop = true;
}

void OnGUI()
{
//绘制电影纹理
GUI.DrawTexture (new Rect (0,0, Screen.width, Screen.height),movTexture,ScaleMode.StretchToFill);

if(GUILayout.Button("播放/继续"))
{
//播放/继续播放视频
if(!movTexture.isPlaying)
{
movTexture.Play();
}

}

if(GUILayout.Button("暂停播放"))
{
//暂停播放
movTexture.Pause();
}

if(GUILayout.Button("停止播放"))
{
//停止播放
movTexture.Stop();
}
}

}



在场景选中一个物体,只移动和旋转这一个物体,选中另

一个,也只移动旋转另一个,不要一起移动或旋转,


//需在场景中创建两个物体做为检测对象
var target1: Transform;
var target2: Transform;
function Update () {
if (Input.GetMouseButton(0)) {
var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit: RaycastHit;
if (Physics.Raycast(ray, hit)) {
if (hit.transform == target1) {
target1.transform.Rotate(0,5,0);
} else if (hit.transform == target2) {
print("Hit target 2");
}
} else {
print("Hit nothing");
}
}
}






角色移动,跳跃
using UnityEngine;
using System.Collections;

public class jiaobenkongzhi : MonoBehaviour
{
[HideInInspector]
public bool facingRight = false; //控制角色朝向
[HideInInspector]
public bool tiaoyue = false; //判断角色是否挑起
public float tiaoyueForce = 1000F;


private bool grounded = false;
private Transform groundCheck;


public float moveForce = 365f;//此变量设置添加的刚体力的大小
public float maxSpeed = 5f;//设置角色的最大移动速度

private Animator anim;

void Awake ()
{
groundCheck = transform.Find ("groundCheck");
anim = GetComponent();
}
void Update ()
{
grounded = Physics2D.Linecast (transform.position, groundCheck.position, 1 << https://www.doczj.com/doc/295696192.html,ToLayer ("renwu"));
Debug.DrawLine (transform.position, groundCheck.position,Color.red,1f);
if (Input.GetButtonDown ("tiaoyue")&&grounded)
tiaoyue = true;
}
void FixedUpdate()
{
float h = Input.GetAxis ("Horizontal");//获取水平输入

//设置转身功能
if (h < 0 && !facingRight)
{
Flip ();
}
else if (h > 0 && facingRight)
{
Flip ();
}
//设置角色行进功能
if (h * rigidbody2D.velocity.x < maxSpeed)
{
rigidbody2D.AddForce(Vector2.right*h*moveForce);
}
if (Mathf.Abs (rigidbody2D.velocity.x) > maxSpeed)
{
rigidbody2D.velocity=new Vector2(Mathf.Sign(rigidbody2D.velocity.x)*maxSpeed,rigidbody2D.velocity.y);
}
Debug.Log (rigidbody2D.velocity.x);
//设置角色跳跃功能
if(tiaoyue)
{
rigidbody2D.AddForce(new Vector2(0f,tiaoyueForce));
tiaoyue = false;
}



}
void Flip()
{
facingRight= !facingRight;

Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}



当摄像机处于跟随主角状态时,那么主角移动后很有可能摄像机被别的模型挡住。这样用户体验就非常不好,一般3D游戏在处理视角的时候有两种方法,第一种是让被挡住的模型变成透明,第二种是拉近摄像机。前者时候固定视角游戏使用,后者适合变化视角游戏使用。两个我们都学一学蛤蛤。

首先,为了方面鼠标与移动平台上的触摸同时相应我写了一个通用的方法。

包括 开始触摸 触摸中 结束触摸 ,电脑手机都可以用这个方法相应到。



using Un

ityEngine;
using System.Collections;

public class JFConst
{

public static bool TouchBegin()
{
if(Input.GetMouseButtonDown(0))
{
return true;
}
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
return true;
}
return false;
}

public static bool TouchEnd()
{
if(Input.GetMouseButtonUp(0))
{
return true;
}
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
return true;
}
return false;
}

public static bool TouchIng()
{
if(Input.GetMouseButton(0))
{
return true;
}else if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
return true;
}
return false;
}

}



第三方摄像机跟随c#
using UnityEngine; using System.Collections;
[AddComponentMenu("controls/ThirdCameraControl")] public class ThirdCameraControlScript : MonoBehaviour {
public Transform cameraTransform;
private Transform target;
public float distance = 7.0f; public float height = 3.0f;
public float angularSmoothLag = 0.3f;
public float angularMaxSpeed = 15.0f; public float heightSmoothLag = 0.3f;
public float snapSmoothLag = 0.2f;
public float snapMaxSpeed = 720.0f;
public float clampHeadPositionScreenSpace = 0.75f;
public float lockCameraTimeout = 0.2f;
private Vector3 headOffset = Vector3.zero; private Vector3 centerOffset = Vector3.zero;
private float heightVelocity = 0.0f;
private float angleVelocity = 0.0f; private bool snap = false;
private ThirdPlayerControlScript controller;
private float targetHeight = 100000.0f; void Start ()
{
if (!cameraTransform && Camera.main)
cameraTransform = Camera.main.transform;
if(!cameraTransform) {
Debug.Log("Please assign a camera to the ThirdPersonCamera script.");
enabled = false;
}
target = transform;
if (target)
controller = target.GetComponent();
if (controller) {
CharacterController characterController = target.GetComponent(); centerOffset = characterController.bounds.center - target.position; headOffset = centerOffset; headOffset.y = characterController.bounds.max.y - target.position.y; } else Debug.Log("Please assign a target to the camera that has a ThirdPersonController script attached."); Cut(target, centerOffset); } void Cut(Transform dummyTarget,Vector3 dummyCenter) { float oldHeightSmooth = heightSmoothLag; float oldSnapMaxSpeed = snapMaxSpeed; float oldSnapSmooth = snapSmoothLag; snapMaxSpeed = 10000; snapSmoothLag = 0.001f;

heightSmoothLag = 0.001f; snap = true; Apply(transform, Vector3.zero); heightSmoothLag = oldHeightSmooth; snapMaxSpeed = oldSnapMaxSpeed; snapSmoothLag = oldSnapSmooth; } float AngleDistance(float a,float b) { a = Mathf.Repeat(a, 360); b = Mathf.Repeat(b, 360); return Mathf.Abs(b-a); } void Apply(Transform dummyTarget,Vector3 dummyCenter) { // Early out if we don't have a target if (!controller) return; Vector3 targetCenter = target.position + centerOffset; Vector3 targetHead = target.position + headOffset; // Calculate the current & target rotation angles计算当前和目标旋转角度 float originalTargetAngle = target.eulerAngles.y; float currentAngle = cameraTransform.eulerAngles.y; // Adjust real target angle when camera is locked当相机锁定时,调整真正的目标角度 float targetAngle=originalTargetAngle; // When pressing Fire2 (alt) the camera will snap to the target direction real quick. //当按下Fire2(alt)相机将很快吸附到目标方向。 // It will stop snapping when it reaches the target //当快到达目标时会停止吸附 if(Input.GetButton("Fire2")) { snap = true; } if(snap) { // We are close to the target, so we can stop snapping now! if (AngleDistance(currentAngle, originalTargetAngle) < 3.0) snap = false; //随着时间的推移逐渐改变一个给定的角度到期望的角度。 currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle,ref angleVelocity, snapSmoothLag, snapMaxSpeed); } // Normal camera motion//正常的相机运动 else { if(controller.GetLockCameraTimer() < lockCameraTimeout) { targetAngle = currentAngle; } // Lock the camera when moving backwards!//当倒退时锁定相机 // * It is really confusing to do 180 degree spins when turning around.//当角度真的很大时,旋转180; if(AngleDistance(currentAngle,targetAngle)>160 && controller.IsMovingBackwards()) { targetAngle += 180; } currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, ref angleVelocity, angularSmoothLag, angularMaxSpeed); } // When jumping don't move camera upwards but only down! if(controller.IsJumping()) { //当跳得真的很高时,我们才向上移动相机 // We'd be moving the camera upwards, do that only if it's really high float newTargetHeight = targetCenter.y + height; if(newTargetHeight

tHeight>5) { targetHeight = targetCenter.y + height; } } else { targetHeight = targetCenter.y + height; } // Damp the height缓冲高度 float currentHeight = cameraTransform.position.y; currentHeight = Mathf.SmoothDamp(currentHeight, targetHeight, ref heightVelocity, heightSmoothLag); // Convert the angle into a rotation, by which we then reposition the camera将角度换成Y轴旋转值,然后我们重新定位相机 Quaternion currentRotation = Quaternion.Euler(0, currentAngle, 0); // Set the position of the camera on the x-z plane to:x-z平面上设置相机的位置在 // distance meters behind the target距离target的meters米背后 cameraTransform.position = targetCenter; cameraTransform.position += currentRotation * Vector3.back * distance; // Set the height of the camera设置相机高度 cameraTransform.position = new Vector3(cameraTransform.position.x, currentHeight, cameraTransform.position.z); SetUpRotation(targetCenter, targetHead); } void LateUpdate () { Apply(transform, Vector3.zero); } void SetUpRotation(Vector3 centerPos,Vector3 headPos) { // Now it's getting hairy. The devil is in the details here, the big issue is jumping of course. //现在越来越多毛病。魔鬼在于细节,当然最大的问题是跳跃。 // * When jumping up and down we don't want to center the guy in screen space. //当跳跃时我们不想相机在屏幕空间的中间上下跳动 // This is important to give a feel for how high you jump and avoiding large camera movements. // 最重要的是我们应该怎么避免感觉相机在产生很大的移动 // * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth. //同时我们不想让他离开屏幕而且我们想让所有的旋转都是平滑 // So here is what we will do:下面就是我们要做的 // // 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis //我们首先让相机沿着Y轴相机,因此也总是在Y轴的中心 // 2. When grounded we make him be centered//当角色着地时我们使角色在相机的中心 // 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold //当角色跳跃时相机保持旋转,当角色头部超出了阈值时我们旋转相机使得角色回到视图(相机)中 // 4. When landing we smoothly interpolate towards centering him on screen //当着地时我们平滑插入使得角色回到屏幕的中心 Vector3 cameraPos = cameraTransform.position; Vector3 offsetTo

Center = centerPos - cameraPos; // Generate base rotation only around y-axis//生成仅仅基于Y轴的旋转 Quaternion yRotation = Quaternion.LookRotation(new Vector3(offsetToCenter.x, 0, offsetToCenter.z)); Vector3 relativeOffset = Vector3.forward * distance + Vector3.down * height; cameraTransform.rotation = yRotation * Quaternion.LookRotation(relativeOffset); //Calculate the projected center position and top position in world space //计算投影中心位置到顶部位置的距离 Ray centerRay = cameraTransform.GetComponent().ViewportPointToRay(new Vector3(0.5f, 0.5f, 1)); Ray topRay = cameraTransform.GetComponent().ViewportPointToRay(new Vector3(0.5f, clampHeadPositionScreenSpace, 1)); //返回沿着射线在distance距离单位的点。 Vector3 centerRayPos = centerRay.GetPoint(distance); Vector3 topRayPos = topRay.GetPoint(distance); //中心射线与顶部射线之间的角度 float centerToTopAngle = Vector3.Angle(centerRay.direction, topRay.direction); float heightToAngle=centerToTopAngle/(centerRayPos.y-topRayPos.y); float extraLookAngle=heightToAngle*(centerRayPos.y-centerPos.y); if(extraLookAngle

相关主题
相关文档 最新文档