变换组件移动物体(附带人物行走实例)

1.变换组件移动物体

1.相关方法

gameObject.GetComponent<T>():获取相应组件的引用。
查找当前游戏物体身上的某个组件,然后保存它的引用。
Transform.Translate(Vector3, Space):移动物体的位置。
游戏物体往某个方向移动;以自身坐标系或世界坐标系。

2.相关参数

Vector3[struct]:三维向量。
向量,可以表示一个方向,也可以表示一个位置。
Space[enum]:空间。
Space.Self:表示物体自身的坐标系。
Space.World:表示物体所在的世界坐标系。
备注:脚本是游戏物体的一部分,一般控制谁的脚本就挂载在谁的身上。

2.键盘控制移动方向

查使用键盘上的“W,A,S,D”来控制游戏物体的前后左右移动。

具体实例:

1、双击player,打开Animator Controller

增加变量,使变量与状态转换关联起来。

 创建混合树。

建两个,运动中和静止时的混合树,并为这两个混合树之间添加状态转换。

 点一下白箭头(从静止到移动),在Inspector视图中找到Conditions,点小加号添加变量speed。

设置Conditions条件(发生状态转换的条件),当Speed比0大时从等待状态到移动状态。

点掉Has Exit Time,Fixed Duration,将Transition Duratio改为0(去掉过渡动画),如下图:

各参数含义参考:https://blog.csdn.net/wangkai19952008/article/details/77101562

再创建一个新的关系(从移动到静止)。

设置Conditions条件(发生状态转换的条件),当Speed比0.9小时从移动状态到等待状态。

其他步骤不变,最后如下图:

 此处设为0.9的原因:人物即使停止行走,但Speed还会是一个很小的正数,如果设的小了就会出现move和wait状态转换反复的情况。

因此也会出现动画显示问题,问题不大,但我不知道怎么解决了......

 2、点一下你的角色,给你的角色添加一个碰撞组件 

代码如下:

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

public class playerControl : MonoBehaviour
{
    private Rigidbody2D _rigidbody2D;
    private Animator _animator;

    private float movespeed = 2f;
    private float x;
    private float y;
    float _x, _y;

    // Start is called before the first frame update
    void Start()
    {
        Application.targetFrameRate = 60;//帧率设置
        //初始化
        _rigidbody2D = GetComponent<Rigidbody2D>();
        _animator = GetComponent<Animator>();
        _x = _y = 0;
    }

    // Update is called once per frame
    void Update()
    {
        x = Input.GetAxis("Horizontal");
        y = Input.GetAxis("Vertical");

        Vector2 dir = new Vector2(x, y) * movespeed;

        Walk(dir);
       
        if(x!=_x||y!=_y)//当方向发生变化时才发生状态转换

        {
            _animator.SetFloat("Speed", dir.sqrMagnitude);
            _animator.SetFloat(name: "moveY", y);
            _animator.SetFloat(name: "moveX", x);
            
            x = _x;
            y = _y;
        }
        


    }

    private void Walk(Vector2 dir)
    {
        _rigidbody2D.velocity = dir;
    }
}
 

参考视频:

https://www.bilibili.com/video/BV1m7411F77s

https://www.bilibili.com/video/BV1q4411q7mM?spm_id_from=333.788.top_right_bar_window_history.content.click

 

posted @ 2022-09-05 21:35  石元  阅读(71)  评论(0编辑  收藏  举报