我有一些问题。
1)我想完全像愤怒的小鸟空间那样制作2d行星:相同的重力,相同的力,相同的下降速度。
2)我不知道重力和力值应该是多少。
3)当我在行星的两边添加一个对象时,它会掉到底部。
4)我希望当一个物体进入重力半径时,它将保持在半径范围内,并且不会从行星中退出。
总而言之:我想完全像在游戏中一样制作《愤怒的小鸟太空》 2d星球。
《愤怒的小鸟空间》的短片:https://www.youtube.com/watch?v=nH1tfaF7yRM。
那是脚本:
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CircleCollider2D), typeof(CircleCollider2D))]
public class Planet : MonoBehaviour
{
public float gravitation = 0.45f;
public float gravitationRadius = 3.5f;
public float rotationSpeed = 0.9f;
private CircleCollider2D gravitationTrigger;
void Start()
{
gravitationTrigger = GetComponents<CircleCollider2D>()[1];
gravitationTrigger.isTrigger = true;
gravitationTrigger.radius = gravitationRadius / transform.localScale.x;
}
void FixedUpdate()
{
foreach (var objectInVicinity in objectsInRange)
{
if (objectInVicinity == null)
{
objectsInRange.Remove(objectInVicinity);
break;
}
float dist = Vector2.Distance(transform.position, objectInVicinity.transform.position);
float gravitationFactor = 1 - dist / gravitationRadius;
Vector2 force = (transform.position - objectInVicinity.transform.position).normalized * gravitation * gravitationFactor;
objectInVicinity.AddForce(force * 200);
objectInVicinity.GetComponent<Rigidbody2D>().drag = 0.5f;
}
}
private List<Rigidbody2D> objectsInRange = new List<Rigidbody2D>();
private void OnTriggerEnter2D(Collider2D collider)
{
var rb = collider.GetComponent<Rigidbody2D>();
if (rb != null)
{
objectsInRange.Add(rb);
}
}
private void OnTriggerExit2D(Collider2D collider)
{
var rb = collider.GetComponent<Rigidbody2D>();
if (rb != null)
{
objectsInRange.Remove(rb);
}
}
}