Thomas
Thomas

Reputation: 3

Unity auto snap function

I am making a PC building game in unity and I want the parts to snap together in a specific position when they are close enough to each other.

So I have created a player that can drag objects around the scene. I have created an object called motherboard and another one called ram and I want them to snap together when their distance < 10. But when I try and run the game, they first snap together and the ram jumped out of the motherboard right away. I have tried different ways to fix this but they didn't work. I can't find a specific tutorial on this either. So I want to see if anyone can point out where is the problems. There is rigidbody and mesh collider in both motherboard and ram. The auto snap ram script(attached to the motherboard):Click here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RamSnap : MonoBehaviour
{
    public GameObject Ram;
    public Vector3 offset = new Vector3(0.053f,3.3f,0.3f);
    public Quaternion offset2 = Quaternion.Euler(0, 0, 0);
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float dist1 = Vector3.Distance(Ram.transform.position, transform.position);
        if (dist1 < 10)
        {
            Ram.transform.position = transform.position + offset;
            Ram.transform.rotation = transform.rotation * Quaternion.Inverse(offset2);
        }
        
    }

}

Upvotes: 0

Views: 56

Answers (1)

SpikyOwl
SpikyOwl

Reputation: 111

I think you should set IsKinematic = true for Rigidbody of ram when you snap it. If you don't, it will fall onto the motherboard and won't stay in place as it is affected by physics. When they, in this case rams, are not snapped, you can set IsKinematic = false so that they can be affected by physics again.

Upvotes: 0

Related Questions