Edit: While I wasn't able to make the code work completely, I believe my question has been sufficiently answered.
I want to make two objects move, react to collisions and other stuff as if they were one.
For example, Objects A and B are entangled.
When Object C rams into Object A and starts moving with it, Object B should start moving with it. When Object B hits a wall, Object A should act like it also hit a wall.
I tried changing position/speed every frame, but this only works when done in one direction.
Now, I want all forces applied to any of the objects to also apply to the other objects entangled to it.
EDIT: The next step is making the thing work with one of the objects moving along a different axis(e.g. the opposite direction of the others) and at a different scale (e.g. speed is proportional to size). So fixed joints, while a working solution for the simplified version of the problem, don't work for me.
UPDATE: Here's the code so far, trying to figure out how to send the other object spinning in the same way as the first one, not sure how to set the position for the force(s?) applied
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class EEScript : MonoBehaviour
{
public List<GameObject> activeObjects;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionStay(Collision collision)
{
OnCollisionEnter(collision);
}
private void OnCollisionEnter(Collision collision)
{
Rigidbody rigidbody = gameObject.GetComponent<Rigidbody>();
foreach (GameObject obj in activeObjects)
{
Rigidbody rb = obj.GetComponent<Rigidbody>();
if (rb is null || rb.gameObject==gameObject) continue;
Debug.Log(collision.gameObject.name+"->"+obj.name);
for (int i = 0; i < collision.contactCount; i++)
{
ContactPoint co = collision.GetContact(i);
Vector3 relativePoint = co.point - rigidbody.centerOfMass;
Vector3 normal = co.normal;
Vector3 impulse = collision.impulse;
if (Vector3.Dot(normal, impulse) < 0f) impulse *= -1;
rb.AddForceAtPosition(impulse, relativePoint + rb.centerOfMass, ForceMode.Impulse);
}
}
}
}
ForceMode.Impulse
was the help I needed. – Dorijan Cirkveni Sep 12 '19 at 13:54