- Home /
Circular movement using AddForce()
Hello,
I'm trying to make "moon rotating around planet like" scene in Unity using physics 2D.
Let's call white circle "moon" and the black one "planet". The purple/pink trail is made by Trail Renderer.
The code is:
void FixedUpdate ()
{
// transform.position is position of "planet"
Vector2 force = transform.position - moon.position;
// velocity vector which is perpendicular to force vector
Vector2 vel = new Vector2( force.y,-force.x);
Rigidbody2D moon_rigidbody = col_tran.GetComponent<Rigidbody2D>();
// velocity_param is just float to adjust velocity
moon_rigidbody .velocity = vel.normalized * velocity_param;
moon_rigidbody .AddForce( force.normalized * moon_rigidbody .velocity.sqrMagnitude / force.magnitude );
}
The equations in code are based on this .
My problem is that the moon is getting closer and closer to the planet. Why is that? I though that the moon will be moving on the same circle hole time. What am I missing?
if you want an uniform circular motion, you should NOT use AddForce, as it will break the uniform movement.
Did you end up figuring out how to do this with physics 2D?
Answer by agmcorp · Aug 09, 2020 at 05:25 PM
@svope I think it's due to the precision of the calculations. I solved like this:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddForce2 : MonoBehaviour
{
public float speed = 2.0f;
public GameObject center;
private Rigidbody2D _rigidbody;
private Transform _transform;
private float _radius;
void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
_transform = GetComponent<Transform>();
_radius = GetDistance(center.transform.position);
AddDistanceJoint2D();
}
void FixedUpdate()
{
Vector2 centripetalForceDirection = (center.transform.position - _transform.position).normalized;
Vector2 tangentVelocityDirection = GetPerPendicularDirection(centripetalForceDirection);
_rigidbody.velocity = tangentVelocityDirection * speed;
}
private float GetDistance(Vector2 center)
{
float x_d = center.x - _transform.position.x;
float y_d = center.y - _transform.position.y;
return (float) Math.Sqrt(x_d * x_d + y_d * y_d);
}
private Vector2 GetPerPendicularDirection(Vector2 v)
{
return (new Vector2(v.y, -v.x)).normalized;
}
private void AddDistanceJoint2D()
{
DistanceJoint2D distanceJoint = gameObject.AddComponent<DistanceJoint2D>();
distanceJoint.connectedBody = center.GetComponent<Rigidbody2D>();
distanceJoint.autoConfigureDistance = true;
distanceJoint.maxDistanceOnly = true;
}
}
Your answer
Follow this Question
Related Questions
Simulate perfect circular motion with addforce 0 Answers
Circular movement of gameobject with rigidbody 1 Answer
Roll a ball camera problem? 1 Answer
Circular movement of the player 0 Answers
How can I calibrate phone accelerometer? 0 Answers