> 技术文档 > 学习游戏制作记录(改进投掷剑的行为)7.27

学习游戏制作记录(改进投掷剑的行为)7.27


1.实现剑跟随飞行方向旋转

修改剑的预制体使剑的朝向对准右x轴

Sword_Skill_Contorl脚本

    private void Update()
    {
        transform.right = rb.velocity;//时刻更新位置
    }

2.实现剑插入地面或者敌人

修改预制体为触发器

Sword_Skill_Contorl脚本:

    private bool canRotate=true;

    private void Update()
    {
        if(canRotate)//可以旋转才能设置速度
        {
        transform.right = rb.velocity;

        }

       
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        canRotate = false;//不能旋转
        cd.enabled = false;//关闭碰撞器

        rb.isKinematic = true;//设置为Kinematic,这是一个运动学状态
        rb.constraints = RigidbodyConstraints2D.FreezeAll;//锁定xyz

        transform.parent = collision.transform;//将剑设置为碰撞到物体的子对象
    }

演示:

3.玩家只能持有1把剑即当一把剑被投掷时不能进入瞄准状态

Player脚本:

    public GameObject sword { get; private set; }//剑的对象

    public void AssignNewSword(GameObject _newSword)//分配
    {
        sword = _newSword;
    }

    public void clearTheSword()//销毁
    {
        Destroy(sword);
    }

Sword_Skill脚本:

player.AssignNewSword(newSword);//在CreatSword()中调用

PlayerGroundedState脚本:

        if(Input.GetKeyDown(KeyCode.Mouse1)&&!_Player.sword)//不持有剑才能按下鼠标右键
        {
            _PlayerStateMachine.ChangeState(_Player.AimSword);
        }

4.玩家再此按下鼠标右键时可以回收剑

Sword_Skill_Control脚本:

    [SerializeField] private float returnSpeed=12f;//返回的速度

    private bool isReturning;//是否返回

    public void SetupSword(Vector2 _dir,float _gravityScale,Player _player)//传入player,作为返回目标,从Sword_Skill脚本中传入
    {
        rb.velocity = _dir;
        rb.gravityScale = _gravityScale;

        player = _player;

        anim.SetBool(\"rotation\", true);//设置旋转动画
    }

    public void ReturnSword()
    {
        rb.isKinematic=false;
        transform.parent = null;//取消原父对象

        isReturning = true;//开始返回
    }

    private void Update()
    {
        if(canRotate)
        {
        transform.right = rb.velocity;

        }

       if(isReturning)
        {
            transform.position = Vector2.MoveTowards(transform.position, player.transform.position, returnSpeed*Time.deltaTime);//向玩家移动

            if(Vector2.Distance(transform.position, player.transform.position)<1)//距离小于1时销毁
            {
                player.clearTheSword();
            }
        }
    }

PlayerGroundedState脚本:

    private bool HasNoSword()//是否投掷出剑
    {
        if (!_Player.sword)//未投掷可以进入瞄准
        {
            return true;
        }

        _Player.sword.GetComponent().ReturnSword();//已经投掷则调用返回函数
        return false;
        
    }

        if(Input.GetKeyDown(KeyCode.Mouse1)&&HasNoSword())//Update中
        {
            _PlayerStateMachine.ChangeState(_Player.AimSword);
        }

演示:

宁夏同心网