Unity对象的简单平移与旋转

物体旋转问题,比如说自转,绕转,点击一物体,让其它物体绕该物体转,还有始终面向鼠标或者是player朝向等等,实际上都是一些简单的Rotate\RotateAround\LookAt等的属性,实现起来很简单,只需要获取场景里的物体,设置相对应的属性就可以。
 
 
 
 
1.场景中物体获取方法:
cube = GameObject.FindGameObjectWithTag(Tags.Cube).transform;
cube1 = GameObject.FindGameObjectWithTag(Tags.Cube1).transform;
cube2 = GameObject.FindGameObjectWithTag(Tags.Cube2).transform;


2.控制移动:
//控制移动
float h = Input.GetAxis ("Horizontal");
float v = Input.GetAxis ("Vertical");
GetComponent<Rigidbody> ().MovePosition (transform.position - new Vector3 (h, 0, v) * speed * Time.deltaTime);


3.始终朝向鼠标方向的实现:
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
//控制转向,朝向鼠标
RaycastHit hitInfo;
if (Physics.Raycast(ray,out hitInfo, 200, groundLayerIndex)) {
    Vector3 target = hitInfo.point;
    target.y = transform.position.y;
    transform.LookAt(target);
}


         平移是通过改变position的方法来实现的,通过设定值与deltaTime的乘积来控制速度,简单实用
        自转是Rotate,绕转是RotateAround,通过光线投放碰撞检测出被作为中心的物体,如果数量比较大可以用数组等等的方式来实现
 
4.点击某物体,其它物体围绕其转
RaycastHit hit;  
if (Input.GetMouseButton (0)) {
	//Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	//RaycastHit hit;  
	if (Physics.Raycast (ray, out hit)) {
		Debug.Log (hit.collider.name);
		//print("hello !");
		//cube旋转
		if (hit.collider.name == "Cube") {
			cube.Rotate (0, 1, 0);
			cube1.RotateAround (cube.position, new Vector3 (0, 5, 0), 60 * Time.deltaTime);
			cube2.RotateAround (cube.position, new Vector3 (0, 5, 0), 60 * Time.deltaTime);
		}
		if (hit.collider.name == "Cube1") {
			cube1.Rotate (0, 1, 0);
			cube.RotateAround (cube1.position, new Vector3 (0, 5, 0), 60 * Time.deltaTime);
			cube2.RotateAround (cube1.position, new Vector3 (0, 5, 0), 60 * Time.deltaTime);
		}
		if (hit.collider.name == "Cube2") {
			cube2.Rotate (0, 1, 0);
			cube1.RotateAround (cube2.position, new Vector3 (0, 5, 0), 60 * Time.deltaTime);
			cube.RotateAround (cube2.position, new Vector3 (0, 5, 0), 60 * Time.deltaTime);
		}
	} 
}

        这几行是用来实现物体始终朝向鼠标方向的代码,像是合金弹头里角色的枪始终朝向鼠标类似。
总结:
         移动旋转等的原理其实很简单,还有一个addforce的方法,像是模拟子弹应该就是这种方法,但是模拟导弹轨迹这类应该都是setPosition,在实际的操作中可以根据需求来具体实现所需的逻辑结构。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值