• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

unity3D物体移动和相机跟随

武飞扬头像
可爱的小昕同学
帮助1

unity中C#文件创建与介绍

创建C#文件的位置在界面的最下面Assets处,创建方法是在下面:
学新通

创建好的界面如下所示:
学新通

创建完C#后双击即可打开,打开后界面如下:
学新通
第一个函数void Start()是只有在代码开始的时候运行一次,不再更新;后面的函数void Update()是在运行过程中每一秒更新一次。

创建人物三维移动

如果想要让我们创建的人物移动,就要通过添加C#插件进行控制,代码如下:

using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;

public class playermove : MonoBehaviour
{
    public float speed;

    public CharacterController playercontroller;

    // Update is called once per frame
    void Update()
    {
        float x, z;
        x = Input.GetAxis("Horizontal");//获取水平状态
        z = Input.GetAxis("Vertical");  //获取垂直状态

        Vector3 move;//创建三维向量(x,y,z)

        move = transform.right * x   transform.forward * z;

        playercontroller.Move(move * speed * Time.deltaTime);
    }
学新通

创建完成后我们就要将将其添加到创建的物体上:点击创建的人物后再点击右侧的“添加组件”,输入我们创建的C#文件名。

创建视野跟随

如果我们想要创建第一人称视角的游戏,就要放一个摄像头在创建的人物上,并跟随人物移动:
代码如下:

using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
using UnityEngine;

public class camerlook : MonoBehaviour
{
    public float MouseSpeed;
    public Transform player;

    private float xmove;
    // Start is called before the first frame update
    void Start()
    {
        //锁定鼠标位置,防止乱跑而造成奇怪的视角
        Cursor.lockState = CursorLockMode.Locked;
    }
    // Update is called once per frame
    void Update()
    {
    	//创建鼠标(摄像机)移动
        float x, y;
        //X上的位移等于鼠标X移动速度乘时间
        x = Input.GetAxis("Mouse X") * MouseSpeed * Time.deltaTime;
        y = Input.GetAxis("Mouse Y") * MouseSpeed * Time.deltaTime;
        xmove = xmove - y;
        //对x方向移动进行限幅,感兴趣可以试试注释掉是什么现象(斜眼笑)
        xmove = Mathf.Clamp(xmove, -90, 90);
        this.transform.localRotation = Quaternion.Euler(xmove, 0, 0);
        //创建三维向量
        player.Rotate(Vector3.up * x);

    }
}
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgafajk
系列文章
更多 icon
同类精品
更多 icon
继续加载