Unity3D如何使用脚本实现跳跃的效果
来源:互联网 发布:网络系统威胁 网络传输 编辑:程序博客网 时间:2024/05/23 02:03
这里介绍的是如何使用脚本最简单的模拟出跳跃的效果。
脚本源码如下:
var speed = 3.0; //This data type is a float.
var jumpSpeed = 50.0;
var grounded = true;
function Update ()
{
var x : Vector3 = Input.GetAxis("Horizontal") * transform.right * Time.deltaTime * speed;
var z : Vector3 = Input.GetAxis("Vertical") * transform.forward * Time.deltaTime * speed;
//transform.Translate(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
transform.Translate(x + z);
transform.rotation = Quaternion.LookRotation(Vector3.forward, Vector3.up);
if(Input.GetButtonDown("Jump"))
{
Jump ();
}
}
function Jump ()
{
if(grounded == true)
{
rigidbody.AddForce(Vector3.up * jumpSpeed);
grounded = false;
}
}
function OnCollisionEnter(hit : Collision)
{
grounded = true;
Debug.Log("I'm colliding with something!");
}
其中,这行代码尤为重要:
1
transform.rotation = Quaternion.LookRotation(Vector3.forward, Vector3.up);
如果注释掉这行代码,物体在跳跃的时候会出现空中翻转的现象,添加后物体不会出现除了z轴之外的其他旋转。
一个完善的角色移动的脚本源码如下:
var speed : float = 6.0;
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;
private var moveDirection : Vector3 = Vector3.zero;
function Update()
{
var controller : CharacterController = GetComponent(CharacterController);
if(controller.isGrounded)
{
moveDirection = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); //Allows for player input
moveDirection = transform.TransformDirection(moveDirection); //How to move
moveDirection *= speed; //How fast to move
if(Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
//Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
//Move the controller
controller.Move(moveDirection * Time.deltaTime);
}
如果想添加动画的话,使用如下代码即可:
function Update()
{
if(Input.GetKey("d") || Input.GetKey("right"))
{
animation.Play("RunFwd");
}
else if(Input.GetKey("a") || Input.GetKey("left"))
{
animation.Play("RunBkwd");
}
else if(Input.GetKey("w") || Input.GetKey("up"))
{
animation.Play("StrafeL");
}
else if(Input.GetKey("s") || Input.GetKey("down"))
{
animation.Play("StrafeR");
}
else
{
animation.CrossFade("Idle");
}
}
0 0
- Unity3D如何使用脚本实现跳跃的效果
- [Unity3D]如何使用脚本模拟出跳跃的效果
- Unity3d 脚本实现CoverFlow 效果
- Unity3d 脚本实现CoverFlow 效果
- Unity3D 脚本实现动画效果
- Unity3d实现人物跳跃
- unity3d 实现简单的水下相机效果脚本代码
- Unity3d GUI实现时钟效果脚本
- Unity3D 4.x如何实现动画的Ping Pong效果
- unity3d中如何让相机实现滑翔的效果
- unity3d使用GUI实现打字机的文字显示效果
- Unity3D实现弹幕的效果
- 如何使用MonoDevelop调试Unity3D脚本
- 如何使用Visual Studio调试Unity3D脚本
- 跳跃表的实现
- 跳跃表的实现
- 跳跃表的实现
- 跳跃表的实现
- ZOJ 3380 Patchouli's Spell Cards (概率dp)
- ZOJ2016 POJ1386(有向图的欧拉路判断)
- [go语言]同时上传表单字段和文件
- hdu 2149 Public Sale(博弈)
- UVa 1533 - Moving Pegs (隐式图搜索 + 状态压缩)
- Unity3D如何使用脚本实现跳跃的效果
- ffmpeg的编译大全(包括 ffmpeg for android)
- 动态生成mybatis的xml文件,其中的sql语句生成
- qq侧滑
- 黑客文化与网络安全听课笔记(上)
- Android Service生命周期 Service里面的onStartCommand()方法详解
- PAT (Basic Level) Practise (中文)1024. 科学计数法 (20)
- HDU1024 Max Sum Plus Plus 【DP】
- Ubuntu 14.04系统安装ThinkPad X201s指纹设备驱动