Unity 2D:引力

问题描述

我正在开发一个小型游戏:我希望将所有GameObjects拉入屏幕的中间,以便它们与另一个GameObject碰撞。

我尝试了这种尝试:

using UnityEngine;
using System.Collections;
public class Planet : MonoBehaviour
{
    public Transform bird;
    private float gravitationalForce = 5;
    private Vector3 directionOfBirdFromPlanet;
 
    void Start ()
    {
        directionOfGameObjectFromMiddle = Vector3.zero;
    }
 
    void FixedUpdate ()
    {
        directionOfGameObjectFromMiddle = (transform.position-bird.position).normalized;
        bird.rigidbody2D.AddForce (directionOfGameObjectFromMiddle * gravitationalForce);    
    }
}

遗憾的是我无法正常工作。有人告诉我,我必须给正在的对象拉另一个脚本,但是是否可以仅使用在拉对象上使用的一个脚本来做到这一点? >?

解决方法

因此,首先,您有很多错字/代码甚​​至无法编译。

您使用例如directionOfBirdFromPlanet一次,但后来称为directionOfGameObjectFromMiddle;)您的Start非常多余。

如前所述,bird.rigidbody2D已被弃用,您应该使用GetComponent<Rigidbody2D>()或什至更好地直接将字段设为

public Rigidbody2D bird;

对于具有多个对象,您只需将它们分配给列表并执行

public class Planet : MonoBehaviour
{
    // Directly use the correct field type
    public List<Rigidbody2D> birds;

    // Make this field adjustable via the Inspector for fine tuning
    [SerializeField] private float gravitationalForce = 5;

    // Your start was redundant    

    private void FixedUpdate()
    {
        // iterate through all birds
        foreach (var bird in birds)
        {
            // Since transform.position is a Vector3 but bird.position is a Vector2 you now have to cast
            var directionOfBirdFromPlanet = ((Vector2) transform.position - bird.position).normalized;

            // Adds the force towards the center
            bird.AddForce(directionOfBirdFromPlanet * gravitationalForce);
        }
    }
}

然后在地球上引用所有bird对象

enter image description here

在鸟类的Rigidbody2D组件上,请确保已设置

Gravity Scale-> 0

您还可以使用Linear Drag进行游戏,因此用简单的话来说,物体在移动时应减慢多少速度

例如Linear Drag = 0就是这样,因此您的对象将以相同的“能量”继续从中心移开

enter image description here

Linear Drag = 0.3会发生这种情况,因此您的对象会随着时间的流逝失去“能量”

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...