C#

Fools ignore complexity; pragmatists suffer it; experts avoid it; CREATIVES remove it.

Friday, November 23, 2018

Mimic an object - Unity C#


Imagine that you want to mimic an object considering its orientation and position but at the same time you don't want to use all of the axis. Here is the way I did it.

using UnityEngine;
using System.Collections;

public class Mimic : MonoBehaviour
{
        public Transform MimicWho;
        public Vector3 OffSet = Vector3.zero;
        public bool MimicPosition = true;
        public bool MimicRotation = true;
public bool IgnoreX = false;
public bool IgnoreY = false;
public bool IgnoreZ = false;
public bool IgnoreRotX = false;
public bool IgnoreRotY = false;
public bool IgnoreRotZ = false;

Vector3 _ignorePos;
Vector3 _ignoreRot;
Vector3 _euler;

    void LateUpdate()
    {
if (MimicRotation)
{
_euler = MimicWho.rotation.eulerAngles;
_ignoreRot = Vector3.zero;
_ignoreRot.x = IgnoreRotX ? 0 : _euler.x;
_ignoreRot.y = IgnoreRotY ? 0 : _euler.y;
_ignoreRot.z = IgnoreRotZ ? 0 : _euler.z;
transform.rotation = Quaternion.Euler(_ignoreRot);
}

if (MimicPosition)
{
_ignorePos = Vector3.zero;
_ignorePos.x = IgnoreX ? 0 : MimicWho.position.x;
_ignorePos.y = IgnoreY ? 0 : MimicWho.position.y;
_ignorePos.z = IgnoreZ ? 0 : MimicWho.position.z;
transform.position = (transform.rotation*OffSet)+_ignorePos;
}
    }
}

Eventually, you may want to mimic it with some damping, then, you can use this next code and  merging both solutions.

using UnityEngine;
using System.Collections;

public class MimicWithDamping : MonoBehaviour
{
    public Transform MimicWho;
    public Vector3 OffSet = Vector3.zero;
    public bool MimicPosition = true;
    public bool MimicRotation = true;
public float Damping = 1;

    void Update()
    {
if (MimicRotation)
transform.rotation = Quaternion.Slerp( transform.rotation, MimicWho.rotation, Time.deltaTime*Damping);

if (MimicPosition)
transform.position = Vector3.Lerp( transform.position, (transform.rotation*OffSet)+MimicWho.position, Time.deltaTime*Damping);
    }
}

:)

Does it implement this interface? (C# Unity)


Does it implement this interface?

Sometimes when using Unity, you need to know, in realtime, if your object has implemented such interface, here is a function that can help.


    static public T HasImplementedInterface(GameObject o)
    {
        return o.GetComponents().OfType().FirstOrDefault();
    }

if you don't want to use RTT System.linq, you can do it even easier:


//imagine an interface called ICarPanel
ICarPanel cp = obj as ICarPanel;
if (cp!=null)
Debug.Log("Implements ICarPanel");


:) !

Powered By Blogger