Unity第一天

158 阅读1分钟

using System; using System.Collections; using System.Collections.Generic; using Unity.VisualScripting; using UnityEngine; public class player : MonoBehaviour { private int i = 0; private GameObject candle; private float x; private float z; private float speed;

private void Awake()
{
    Debug.Log("唤醒时执行");
}
//生命周期函数 只会执行一次
void Start()
{
    //拿到蜡烛 使用标签来拿蜡烛
    candle = GameObject.FindWithTag("candle");

    Debug.Log(candle.name);
    //物体有2个坐标,世界坐标,局部坐标
    Debug.Log($"世界坐标{candle.transform.position}");
    Debug.Log($"局部坐标{candle.transform.localPosition}");
    Debug.Log($"局部X坐标{candle.transform.localPosition.x}");
    Debug.Log($"局部Y坐标{candle.transform.localPosition.y}");
    Debug.Log($"局部Z坐标{candle.transform.localPosition.z}");




}

// Update is called once per frame
void Update() //Time.deltaTime 获取上一帧到当前这一帧的时间
{
    i++;
    /*
      if (i > 2)
    {
        //Debug.Log($"这是第{i}帧,上一帧到现在的时间为{Time.deltaTime}");
        //2*Time.deltaTime 每秒移动2个单位
        //  candle.transform.Translate(2*Time.deltaTime, 0, 0); //每帧移动一 每秒移动1/Time.deltaTime*1(每秒移动多少帧)
        // candle.transform.Translate(Vector3.forward * Time.deltaTime * 2);
        //按键判断,提供一个虚拟轴 为什么要提供虚拟轴呢

    
    }
    */

    //Input类 每个轴对应的偏移量
    x = Input.GetAxis("Horizontal");
    z = Input.GetAxis("Vertical");

    //改变物体的方向 朝向dir
    Vector3 dir = new Vector3(x, 0, z);
    transform.rotation = Quaternion.LookRotation(dir);

    //向前走
    transform.Translate(Vector3.forward * Time.deltaTime);

    //物体加速 拿到x^2+z^2 
    speed = Mathf.Sqrt(x * x + z * z) * 10;
    transform.Translate(Vector3.forward * Time.deltaTime * speed);

}

}

摄像机跟随

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

public class camera : MonoBehaviour {

private Vector3 dir;
private GameObject player;
// Start is called before the first frame update
void Start()
{
    player = GameObject.FindWithTag("candle");
    dir= player.transform.position - transform.position;

}

// Update is called once per frame
void Update()
{
    transform.position = player.transform.position - dir ;
}

}