一步一步操作:
1.创建一个工程
2.在 GameObject 中选择 Create Other/ Shpere, 创建一个球体。
3.点击Ball,在监视器中设置Position x=0,y=2,z=0;
4. 同样的过程创建一个 Cube,重命名为Paddle,设置Scale 以及 Position,保证在Ball 的正下方;
5. File/Save , 存储场景文件
6.添加一个 GameObject|Create Other| Directional Light
7. 在监视器中设置 light 的position , Rotation,使光照向Ball 以及 Paddle
8,. 点击Ball, 设置 Component | Physics | Rigidbody
9. 在刚体重点击 Use Gravity, 使用重力,此时,运行项目,可以看见球一直往下掉,直到落到Paddle 上面
Code :
1. 在Assets 中右键,Create 中选中 JavaScripts
2. 在出现的代码文件中, Update部分修改如下:
input.mousePosition :the current mouse position in pixel coordinates. 用减去halfW 是为了获得负值,可以控制paddle 的左运动Debug.log() : 是实时显示变量的信息;
3.写完代码,把代码文件拖动到Hierarchy 中的Ball 上面,运行工程,鼠标点击控制paddle的左右,以及旋转运动,接住自然往下掉的球。
function Update () {
var halfW:float = Screen.width/2;
transform.position.x = (Input.mousePosition.x - halfW)/halfW;
var halfH:float = Screen.height/2;
transform.position.z = (Input.mousePosition.y - halfH)/halfH;
//Smoothly tilts a transform towards a target ratation
var tiltAroundZ = Input.GetAxis("Mouse X") * tiltAngle;
var tiltAroundX = Input.GetAxis("Mouse Y")*tiltAngle;
var target = Quaternion.Euler(tiltAroundX,0,tiltAroundZ);
//Dampem towards the target rotation
transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);
Debug.Log((Input.mousePosition.x - Screen.width/2)/Screen.width/2);
//transform.position.x = Input.mousePosition.x;
//Debug.Log(Input.mousePosition.x);
}
效果如下, 不过这个球还真难接住,总是会滚下去了
reference:
《Unity3D Game develop by example》