c#代码用于unity——让人物动起来

首先把代码实现给大家放出来:

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

public class PlayerControl : MonoBehaviour
{
    private Animator ani;
    private Rigidbody2D rBody;
    // Start is called before the first frame update
    void Start()
    {
        ani=GetComponent<Animator>();
        rBody=GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        if(horizontal!=0)
        {
            ani.SetFloat("Horizontal", horizontal);
            ani.SetFloat("Vertical", 0);
        }
        if (vertical != 0)
        {
            ani.SetFloat("Horizontal",0);
            ani.SetFloat("Vertical", vertical);
        }
        Vector2 dir = new Vector2(horizontal, vertical);
        ani.SetFloat("Speed",dir.magnitude);
        rBody.velocity = dir * 0.5f;
    }
}

下面我们来做详细解释:

1、引入命名空间

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

这些命名空间用于引入所需的类和功能。
System.Collections System.Collections.Generic 包含一些常用的集合类和泛型集合类。
UnityEngine 是Unity引擎的核心命名空间,包含所有Unity的功能和组件。

2、脚本类和组件

public class PlayerControl : MonoBehaviour

 定义了一个名为 PlayerControl 的公共类,它继承自 MonoBehaviour 类。这意味着我们可以使用 MonoBehaviour 类提供的所有功能,并且可以附加这个脚本到任何Unity对象上。

3、属性

    private Animator ani;
    private Rigidbody2D rBody;

 定义了两个私有变量:
ani: 存储对Animator组件的引用。Animator组件用于控制角色的动画。
rBody: 存储对Rigidbody2D组件的引用。Rigidbody2D组件用于模拟2D物理运动。

 4. Start() 方法

    void Start()
    {
        ani=GetComponent<Animator>();
        rBody=GetComponent<Rigidbody2D>();
    }

 在 Start() 方法中,我们使用 GetComponent() 函数获取 Animator 和 Rigidbody2D 组件的引用,并将其存储在相应的变量中。

 5. Update() 方法

    void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        if(horizontal!=0)
        {
            ani.SetFloat("Horizontal", horizontal);
            ani.SetFloat("Vertical", 0);
        }
        if (vertical != 0)
        {
            ani.SetFloat("Horizontal",0);
            ani.SetFloat("Vertical", vertical);
        }
        Vector2 dir = new Vector2(horizontal, vertical);
        ani.SetFloat("Speed",dir.magnitude);
        rBody.velocity = dir * 0.5f;
    }

在 Update() 方法中,我们每帧都会获取用户的输入(水平轴和垂直轴)。然后,我们根据输入更新 Animator 组件的值,并使用这些值来设置角色的速度和方向。
Input.GetAxisRaw() 函数获取用户输入的原始轴值。
检查水平轴和垂直轴的值,如果不为0,则设置相应的动画参数。
创建一个 Vector2 对象 dir,表示角色的移动方向。
使用 ani.SetFloat() 方法设置角色的速度和方向。
使用 rBody.velocity 设置角色的实际速度。

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值