我正在开发一个小型游戏:我希望将所有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);
}
}
遗憾的是我无法正常工作。有人告诉我,我必须给正在的对象拉另一个脚本,但是是否可以仅使用在拉对象上使用的一个脚本来做到这一点? >?
答案 0 :(得分:2)
因此,首先,您有很多错字/代码甚至无法编译。
您使用例如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
对象
在鸟类的Rigidbody2D
组件上,请确保已设置
Gravity Scale
-> 0
您还可以使用Linear Drag
进行游戏,因此用简单的话来说,物体在移动时应减慢多少速度
例如Linear Drag = 0
就是这样,因此您的对象将以相同的“能量”继续从中心移开
Linear Drag = 0.3
会发生这种情况,因此您的对象会随着时间的流逝失去“能量”