How do I connect two objects that can move together? When one of the objects is moved, I want the other to move on
I am using unity2d
this first object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
[System.Serializable]
public class control : MonoBehaviour {
public Vector3 rotationsPerSecond = new Vector3(0.0f, 0.0f, 0.1f);
Transform RotationTransform;
public float speed;
void Start ()
{
}
void Update ()
{
if (Input.GetKey(KeyCode.UpArrow))
{
transform.position += Vector3.up * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.position += Vector3.down * speed * Time.deltaTime;
}
}
}
this second object:
using System.Collections;
public class control2 : MonoBehaviour
{
float originalY;
private Rigidbody rgb;
public float floatStrength = 1; // You can change this in the Unity Editor to
// change the range of y positions that are possible.
public float speed;
public Transform target;
void Start()
{
this.originalY = this.transform.position.y;
rgb = GetComponent<Rigidbody> ();
}
private Vector3 currentDirection = Vector3.zero;
void Update()
{
transform.position = new Vector3(transform.position.x,
originalY + ((float)Math.Sin(Time.time) * floatStrength),
transform.position.z);
if (currentDirection.Equals(Vector3.zero))
{
Vector3 inputDirection = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
if (!inputDirection.Equals(Vector3.zero))
{
currentDirection = inputDirection;
rgb.velocity = currentDirection * speed;
}
}
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
void OnCollisionEnter2D(Collision2D col)
{
currentDirection = Vector3.zero;
rgb.velocity = Vector3.zero;
}
}