Unity3d之物体运动(一)

在游戏场景中使物体运动的方式,我目前是找到了两种方法。
如果你会其他的方法,欢迎在评论区里交流。

一、利用transform

API传送门:
https://docs.unity3d.com/ScriptReference/Transform.html

方法没只截取一部分,不要求全会,看别的教程时,用哪个会哪个就行 。
在这里插入图片描述

1.旋转运动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player1 : MonoBehaviour {

	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {
	//创建一个三维向量
	//使物体围绕y轴持续旋转
    	transform.Rotate(new Vector3(0.0f,2.0f,0.0f));  
	}
}

在这里插入图片描述

transform:

物体的位置、旋转和尺度。

场景中的每一个物体都有一个变换。它用来存储和操作物体的位置、旋转和比例。

transform.Rotate:

使用Transform.Rotate以多种方式旋转游戏对象。旋转通常作为欧拉角,而不是四元数。

2.前(后左右)移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player1 : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        //new 一个三维向量
        //使物体持续沿x(对应改变向量中的值)轴正方向移动
        //数值越大移动速度越快
        transform.Translate(new Vector3(0.3f, 0.0f, 0.0f));
    }
}

在这里插入图片描述

二、利用刚体

刚体:使物体具有物理的性质,例如使物体具有重力,摩擦力等。

刚体的创建 :
1.先在Hierarchy面板中创建一个物体
2.在Add Component中搜索"Rigidbody"并添加
在这里插入图片描述
在这里插入图片描述
注意:1.要在游戏物体的下面建一个平面,不然游戏物体有了重力的物理性质,会一直下坠。
2.要是Sphere类型 物体,不然会报错。

在这里插入图片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player1 : MonoBehaviour {

    private Rigidbody rd;      //创建一个刚体类型的对象
	// Use this for initialization
	void Start () {
        rd = GetComponent<Rigidbody>();     //得到当前物体的刚体组件属性,并赋值给rd
	}
	
	// Update is called once per frame
	void Update () {
        //AddForce()相当于给物体一个力,使物体进行运动
        //新建一个向量相当于力的方向,并设置力的大小
        //数值越大,运动越快
        rd.AddForce(new Vector3(1, 0, 0));   
	}
}

在这里插入图片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player1 : MonoBehaviour
{

    private Rigidbody rd;      //创建一个刚体类型的对象
                               // Use this for initialization
    void Start()
    {
        rd = GetComponent<Rigidbody>();     //得到当前物体的刚体组件属性,并赋值给rd
    }

    // Update is called once per frame
    void Update()
    {
        //AddForce()相当于给物体一个力,使物体进行运动
        
        rd.AddForce(transform.forward * 1.0f);
    }
}

在这里插入图片描述
GetComponent<要检索的组件类型>()

AddForce

  • 向刚体添加力,力是沿着force矢量。指定作用力模式 mode允许将力的类型改变为加速度、脉冲或速度变化。
  • 作用力计算FixedUpdate或者通过显式调用Physics.Simulate方法。
  • force只能适用于一个活跃的刚体。如果游戏对象是非活动的,则AddForce没有任何效果(例如正方体)。而且,刚体不可能是运动学的。
  • 默认情况下,一旦施加了force,刚体的状态将被设置为“awake”,除非该力是Vector3.zero.
发布了55 篇原创文章 · 获赞 47 · 访问量 3509

猜你喜欢

转载自blog.csdn.net/qq_42577542/article/details/105092246
今日推荐