Unity3D一些简单的实现

发布于 2022-11-20  142 次阅读


刚刚开始学习unity,如果有更好的方法,请教教我!万分感谢!

 

摄像机固定到物体,跟随物体移动

简单的写法

public class CameraMove : MonoBehaviour
{
    // Start is called before the first frame update

    Vector3 Dir;
    //要跟随的物体
    public GameObject Player;
    // Use this for initialization
    void Start()
    {
        //获取到摄像机于要跟随物体之间的距离
        Dir = Player.transform.position - transform.position;
    }

    //LateUpdate是在所有Update函数调用后被调用
    void LateUpdate()
    {
        //摄像机的位置
        transform.position = Player.transform.position - Dir;
    }

}

 

将屏幕鼠标位置转换到世界位置

这里我只是想获取平面坐标x、z,忽略高度y。

// 相机是世界的,世界到屏幕
Vector3 camera = Camera.main.WorldToScreenPoint(firePoint.position);
Vector3 pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, camera.z);
Vector3 mousePoint = Camera.main.ScreenToWorldPoint(pos);
mousePoint.y = 0;

 

解决角色斜向移动速度变快

初中学过的知识已经完全不记得了。。。

        if (forword && left)
        {
            float z = Time.deltaTime * playerSpeed;
            float x = Time.deltaTime * -playerSpeed;
            movePoint.z = z * Mathf.Sqrt(1 - (x * x) / 2);
            movePoint.x = x * Mathf.Sqrt(1 - (z * z) / 2);
            this.transform.Translate(movePoint, Space.Self);
        }

 

使用slider制作一个简易血条

创建一个slider

2022-11-20 130718.jpg

将大小与位置调整一下,选择一个血条的颜色,将Image Type选择为Filled,滑动下方的fillAmount就可以看见滑块的效果。

1668921069573.png

使用脚本控制FillAmount的值,就可以达到效果。

    private void BarFiller()
    {
        //血条始终面向屏幕
        Camera camera = Camera.main;
        playerHeathBar.transform.LookAt(playerHeathBar.transform.position + (camera.transform.rotation * Vector3.back), camera.transform.rotation * Vector3.up);

        PlayerLogic logic = this.GetComponentInParent<PlayerLogic>();
        float maxHealth = logic.maxHealth;
        float health = logic.health;
        //使用MathF.Lerp平滑血条滑动 lerpSpeed滑动速度
        playerHeathBar.fillAmount = Mathf.Lerp(playerHeathBar.fillAmount, health / maxHealth, lerpSpeed * Time.deltaTime);
    }

 


啦啦啦!