C# 统一-当所有元素进入特定区域时减慢其速度

C# 统一-当所有元素进入特定区域时减慢其速度,c#,unity3d,vector,C#,Unity3d,Vector,我想开发一个游戏(2D),你可以在其中放置“时间泡泡”,里面的每个物体都会减慢它的运动 在“时间泡泡”的脚本中,我尝试了以下方法: using System.Collections; using System.Collections.Generic; using UnityEngine; public class TimeBubble : MonoBehaviour { private void OnTriggerEnter2D(Collider2D other) { GameObj

我想开发一个游戏(2D),你可以在其中放置“时间泡泡”,里面的每个物体都会减慢它的运动

在“时间泡泡”的脚本中,我尝试了以下方法:

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

public class TimeBubble : MonoBehaviour {
private void OnTriggerEnter2D(Collider2D other)
{

    GameObject temp = GameObject.Find(other.name);

    temp.GetComponent<Rigidbody>().velocity = Vector3.zero;
    temp.GetComponent<Rigidbody>().angularVelocity = Vector3.right * 0;

    }

}
使用系统集合;
使用System.Collections.Generic;
使用UnityEngine;
公共类时间泡沫:单一行为{
私有无效OnTiggerEnter2D(碰撞R2D其他)
{
GameObject temp=GameObject.Find(其他.name);
temp.GetComponent().velocity=Vector3.0;
temp.GetComponent().angularVelocity=Vector3.right*0;
}
}
这是行不通的

有人知道如何减慢气泡内的所有元素吗?

观察

  • 如果你有另一个脚本改变速度,比如charachter控制器,你不能从这个脚本设置速度,你需要将speedReductionFactor传递给你的charachter控制器,并使用它和输入逻辑更新那里的速度,我将把它留给你

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class TimeBubble : MonoBehaviour {
    
        [Range(0,1)]
        public float speedReductionFactor = .5f;
    
        List <GameObject> objectsInside;
    
        Rigidbody2D rb;
    
        void Start ()
        {
            objectsInside = new List<GameObject>();
        }
    
        void OnTriggerEnter2D(Collider2D other) {
            rb = other.gameObject.GetComponent<Rigidbody2D>();
            if (rb == null)
                return;
            rb.velocity *= speedReductionFactor;
            objectsInside.Add(other.gameObject);
        }
    
        void OnTriggerExit2D (Collider2D other){
            rb = other.gameObject.GetComponent<Rigidbody2D>();
            if (rb != null && objectsInside.Contains(other.gameObject)) {
                rb.velocity *= (1 / speedReductionFactor);
                objectsInside.Remove(other.gameObject);
            }
        }
    
    }
    
    使用系统集合;
    使用System.Collections.Generic;
    使用UnityEngine;
    公共类时间泡沫:单一行为{
    [范围(0,1)]
    公共浮动速度降低系数=.5f;
    在旁边列出对象;
    刚体2d rb;
    无效开始()
    {
    objectsInside=新列表();
    }
    无效OnTiggerEnter2D(碰撞的R2D其他){
    rb=other.gameObject.GetComponent();
    if(rb==null)
    返回;
    rb.速度*=速度折减系数;
    objectsInside.Add(other.gameObject);
    }
    无效OnTriggerExit2D(碰撞的R2D其他){
    rb=other.gameObject.GetComponent();
    if(rb!=null&&objectsInside.Contains(other.gameObject)){
    rb.速度*=(1/速度折减系数);
    objectsInside.Remove(其他.gameObject);
    }
    }
    }
    
“不工作”不是问题陈述。你需要说明发生了什么,你期望什么