当前位置:   article > 正文

Untiy 使用RotateAround()方法实现物体围绕某个点或者某个物体旋转_unity围绕旋转

unity围绕旋转

Untiy 实现物体围绕指定点或者某个物体旋转,可使用RotateAround()方法。

语法:

public void RotateAround(Vector3 point, Vector3 axis, float angle);

其中,point:旋转中心点位置;
axis:要围绕的轴,如x,y,z
angel:旋转的角度

该方法可以实现物体围绕指定的中心点和轴旋转。

下面举例实现围绕某个点旋转和围绕某个物体旋转。

1、围绕某个点旋转。

在场景中创建一个球体。然后编写以下脚本:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class RotateTest : MonoBehaviour
  5. {
  6. public float rotationSpeed = 0.01f;
  7. public Transform tran;
  8. // Start is called before the first frame update
  9. void Start()
  10. {
  11. }
  12. // Update is called once per frame
  13. void Update()
  14. {
  15. tran.RotateAround(new Vector3(10f,0f,0f), Vector3.up* rotationSpeed, 1f);
  16. }
  17. }

把脚本放到场景中,并把球体拉到tran参数中,运行场景,球体就会围绕着坐标为(10f,0f,0f),Y轴方向旋转,每帧旋转角度为1。

这里围绕的轴常用的是围绕X轴、Y轴、Z轴,表示法可参考以下:

  1. //X轴表示法
  2. Vector3.right
  3. new Vector3(1,0,0)
  4. //Y轴表示法
  5. Vector3.up
  6. new Vector3(0,1,0)
  7. //Z轴表示法
  8. Vector3.forward
  9. new Vector3(0,0,1)

2、围绕某个物体旋转,方法大抵相同,主要是要把第一个参数设置为物体的坐标,第二个参数为沿着物体的轴。

同样创建一个球体和一个物体:

创建以下代码:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class RotateTest : MonoBehaviour
  5. {
  6. public float rotationSpeed = 0.01f;
  7. 、、public Transform tran;
  8. public Transform tran1;
  9. public Transform Obj;
  10. // Start is called before the first frame update
  11. void Start()
  12. {
  13. }
  14. // Update is called once per frame
  15. void Update()
  16. {
  17. //tran.RotateAround(new Vector3(10f,0f,0f), Vector3.up* rotationSpeed, 1f); //围绕点旋转
  18. tran1.RotateAround(Obj.position, Obj.up * rotationSpeed, 1f); //围绕物体旋转
  19. }
  20. }

把脚本拉到场景中,把球体赋予tran1,物体赋予Obj,那么就可以实现球体围绕着物体旋转。

最终效果:

Untiy 实现物体围绕指定点或者某个物体旋转

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/40724
推荐阅读
相关标签
  

闽ICP备14008679号