首页 > 解决方案 > 运算符“*”不能应用于“void”和“float”类型的操作数

问题描述

***

使用 System.Collections;使用 System.Collections.Generic;使用 UnityEngine;公共类击退:MonoBehaviour {公共浮动推力;公共浮动敲门声;

// Start is called before the first frame update
void Start()
{
    
}
// Update is called once per frame
void Update()
{
    
}
private void OnTriggerEnter2D(Collider2D other)
{
    if(other.gameObject.CompareTag("enemy"))
    {
        Rigidbody2D enemy = other.GetComponent<Rigidbody2D>();
        if(enemy != null)
        {
            StartCoroutine(KnockCo(enemy));
        }
    }
}
private IEnumerator KnockCo(Rigidbody2D enemy)
{
    if(enemy != null)
    {
        Vector2 forceDirection = enemy.transform.position - transform.position;
        Vector2 force = forceDirection.Normalize() * thrust;
        
        enemy.velocity = force;
        yield return new WaitForSeconds(KnockTime);
       
       enemy.velocity = new Vector2();
       {
       }
    }
} }

标签: c#

解决方案


forceDirection.Normalize()改变forceDirection向量并返回void,而不是返回归一化的向量。因此,您需要将Normalize()调用和乘法拆分为单独的语句:

Vector2 forceDirection = enemy.transform.position - transform.position;
forceDirection.Normalize();
Vector2 force = forceDirection * thrust;

推荐阅读