Unity 3D基本的移动操作

一、使用transform组件进行移动

transform组件是每一个游戏物体自带的组件,它表示的是Object的外在改变,里面的属性如图所示:

 Position-->Object的位置.  Rotation-->对Object进行旋转. Scale-->对Object进行缩放

而且Transform组件有很多内置方法,比如这次移动用到的就是--Translate方法.

实例代码如下:

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

public class move2 : MonoBehaviour
{

    public float moveSpeed;
    private float x_direction;
    private float z_direction;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        x_direction = Input.GetAxis("Horizontal");
        z_direction = Input.GetAxis("Vertical");
        this.transform.Translate(x_direction * moveSpeed, 0, z_direction * moveSpeed);
    }
}

这样就可以实现一个简单的Object移动.Translate里面的可以是一个三维向量当作参数.

二、使用Rigidbody组件进行移动

Mass-->质量.   Drag-->阻力.   Angular Drag-->角阻力.   Use Gravity-->重力模式.  

Is Kinematic --> 是一种很自由的运动,抛开重力 

关于Interpolate和Collision Detection 笔者也没有用过,所以无法告知大家了.有大佬会的麻烦在评论区告诉我一声呗..

扫描二维码关注公众号,回复: 16179687 查看本文章

Constraints-->约束...下面分别是冻结位置和冻结旋转.

那么我们怎么使用Rigidbody来控制物体移动呢?    简单!!!!!

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

public class move2 : MonoBehaviour
{
    private Rigidbody rb;
    public float moveSpeed;
    private float x_direction;
    private float z_direction;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>(); 
    }

    // Update is called once per frame
    void Update()
    {
        x_direction = Input.GetAxis("Horizontal");
        z_direction = Input.GetAxis("Vertical");
        rb.velocity = new Vector3(x_direction * moveSpeed, 0, z_direction * moveSpeed);        
    }
}

我们利用的是Rigidbody.velocity这个属性,这个属性可以获取当前Object的速度.只需要创建一个矢量单位,并且根据输入操作判断方向,就可以实现Object在这个方向移动.

三、利用鼠标控制移动

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

public class move2 : MonoBehaviour
{

    Vector3 tempPoint = new Vector3(0, 0, 0);

    // Start is called before the first frame update
   

    // Update is called once per frame
    void Update()
    {
        PlayerMove_FollowMouse();
    }

    private void PlayerMove_FollowMouse()
    {
        if(Input.GetMouseButtonDown(1))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                tempPoint = hitInfo.point;
            }
        }
        float step = 10 * Time.deltaTime;
        this.transform.localPosition = Vector3.MoveTowards(this.transform.localPosition, tempPoint, step);
        this.transform.LookAt(tempPoint);

        

    }
}

 行啦,笔者不才.目前还是一个新手会的移动控制只有这么多了

如果对您有所帮助,请关注一下吧........

猜你喜欢

转载自blog.csdn.net/2203_76113052/article/details/129647841