User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active

Follower 2D

Needed: Unity Free or Pro

Simple but accurate follow script for 2D rigidbodies. Just attach it to a 2D game object and assign a target.

When you had problems with the orientation of your Ridgidody2D while following an object have a look to this script.

Code

using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class Follower2D : MonoBehaviour 
{
    /// <summary>
    /// The target <c>GameObject</c>.
    /// </summary>
    public GameObject Target;

    public float MoveSpeed = 2, AngularSpeed = 45;

    /// <summary>
    /// Angle threshold. When the angle is smaller than this value, no recalculations are performed.
    /// </summary>
    public const float Threshold = 1e-3f;

    public void Update()
    {
        LookAt();
        Move();
    }

    /// <summary>
    /// Looks at the <c>Target</c> game object.
    /// </summary>
    public void LookAt()
    {
        Vector2 dir = transform.InverseTransformPoint(Target.transform.position);

        float angle = Vector2.Angle(Vector2.right, dir);

        angle = dir.y < 0 ? -angle : angle;

        if (Mathf.Abs(angle) > Threshold)
        {
            transform.Rotate(Vector3.forward, AngularSpeed * Time.deltaTime * Mathf.Sign(angle));
        }
    }

    /// <summary>
    /// Moves toward the target.
    /// </summary>
    public void Move()
    {
        rigidbody2D.MovePosition(transform.position +  (transform.right * MoveSpeed * Time.deltaTime));
    }
}

 

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active

Triangle Intersection

Needed: Unity Free or Pro

Möller-Trumbore triangle intersection implementation for Unity 3D.

Code

    /// <summary>
    /// Checks if the specified ray hits the triagnlge descibed by p1, p2 and p3.
    /// Möller–Trumbore ray-triangle intersection algorithm implementation.
    /// </summary>
    /// <param name="p1">Vertex 1 of the triangle.</param>
    /// <param name="p2">Vertex 2 of the triangle.</param>
    /// <param name="p3">Vertex 3 of the triangle.</param>
    /// <param name="ray">The ray to test hit for.</param>
    /// <returns><c>true</c> when the ray hits the triangle, otherwise <c>false</c></returns>
    public static bool Intersect(Vector3 p1, Vector3 p2, Vector3 p3, Ray ray)
    {
        // Vectors from p1 to p2/p3 (edges)
        Vector3 e1, e2;  

        Vector3 p, q, t;
        float det, invDet, u, v;


        //Find vectors for edges sharing vertex/point p1
        e1 = p2 - p1;
        e2 = p3 - p1;

        // Calculate determinant 
        p = Vector3.Cross(ray.direction, e2);

        //Calculate determinat
        det = Vector3.Dot(e1, p);

        //if determinant is near zero, ray lies in plane of triangle otherwise not
        if (det > -Epsilon && det < Epsilon) { return false; }
        invDet = 1.0f / det;

        //calculate distance from p1 to ray origin
        t = ray.origin - p1;

        //Calculate u parameter
        u = Vector3.Dot(t, p) * invDet;

        //Check for ray hit
        if (u < 0 || u > 1) { return false; }

        //Prepare to test v parameter
        q = Vector3.Cross(t, e1);

        //Calculate v parameter
        v = Vector3.Dot(ray.direction, q) * invDet;

        //Check for ray hit
        if (v < 0 || u + v > 1) { return false; }

        if ((Vector3.Dot(e2, q) * invDet) > Epsilon)
        { 
            //ray does intersect
            return true;
        }

        // No hit at all
        return false;
    }

 

 

 

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active

Flickering Light

Needed: Unity Free or Pro

Advanced script component that adds a realistic, fully adjustable flicker effect to every light source.

Code

using UnityEngine;

/// <summary>
/// Adds a realistic flickering behaviour to any light source.
/// Version 1.1
/// Copyright by &u Assets 2014.
/// </summary>
public class Flicker : MonoBehaviour 
{
    //------------------------
    // Public Fields
    //------------------------

    /// <summary>
    /// The min intensity (amplitude) of the flicker function.
    /// </summary>
    [Range(0f, 10f)]
    public float Min = 1;

    /// <summary>
    /// The max intensity (amplitude) of the flicker function.
    /// </summary>
    [Range(0.001f, 10f)]
    public float Max = 1.5f;

    /// <summary>
    /// The frequency of the flicker.
    /// </summary>
    [Range(0.001f, 120)]
    public float Frequency = 6;

    /// <summary>
    /// The max duration in seconds [s] of a pause.
    /// </summary>
    [Range(0f, 60f)]
    public float MaxPauseTime = 0.75f;

    /// <summary>
    /// The min duration in seconds [s] of a pause.
    /// </summary>
    [Range(0f, 50f)]
    public float MinPauseTime = 0.1f;

    /// <summary>
    /// The probability that pause will occure [0..1]. 
    /// 0: There will be no pauses at all.
    /// 1: There will be pause after pause. That means the light will flicker with periode of the pause time.
    /// </summary>
    [Range(0f, 1f)]
    public float PauseChance = 0.5f;

    /// <summary>
    /// The scaling value of the smoothing function. 
    /// When set to a value greater than 1, the target value will be reached faster.
    /// When set to a value less than 1, the target value will be reached slower.
    /// </summary>
    [Range(0.001f, 10)]
    public float SmoothingFactor = 1;

    public bool Smooth = false;

    //------------------------
    // Private Fields
    //------------------------
    private float intensity, lastIntensity;
    private float nextPause = float.MaxValue;
    private float fraction = 0.05f;
    private float t = 0;
    private bool reset = true;

    //------------------------
    // Methods
    //------------------------

	void Start () 
    {
        // Initially call the flicker method
        DoFlicker();
	}

    void Update()
    {
        // interpolate if smoothing is enabled
        if (Smooth)
        {
            // Reset 
            if(reset)
            {
                t = 0;
                reset = false;
            }

            // Integrate over time
            t += Time.deltaTime;

            // Linearly interpolate between intensities
            light.intensity = Mathf.Lerp(lastIntensity, intensity, t * SmoothingFactor);
        }
    }

    void DoFlicker()
    {
        // Probability that a pause will occure between flickers
        float chance = Random.Range(0f, 1f);

        // Compute the next call time
        float next = 1f / Frequency;

        // Rest smoothing step in update
        reset = true;

        // Is there a pause?
        if (chance <= PauseChance)
        {
            next = Random.Range(MinPauseTime, MaxPauseTime);
        }

        // Set last intensity for interpolation
        lastIntensity = intensity;
        intensity = Random.Range(Min, Max);

        // Check if intensity smoothing is enabled
        if (!Smooth)
        {
            light.intensity = intensity;
        }

        // recursively invoke 'DoFlicker()'
        Invoke("DoFlicker", next);
    }
}

 

 

Basic Bullet Hole

Needed: Unity Free or Pro, EasyDecal

This snippet shows how to implement simple bullet hole functionality to your game with EasyDecal system.

Code

using UnityEngine;
using System.Collections;
using ch.sycoforge.Decal;

/// <summary>
/// Demo class for runtime decal placement.
/// </summary>
public class DynamicDemo : MonoBehaviour 
{

    public EasyDecal DecalPrefab_A;

	
	// Update is called once per frame
	void Update () 
    {
        if (Input.GetMouseButtonUp(0))
        {
            // Shoot a ray thru the camera starting at the mouse's current screen space position
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            // Check if ray hit something
            if (Physics.Raycast(ray, out hit, 200))
            {
                // Draw a line along the projection axis for visalizing the projection process.
                Debug.DrawLine(ray.origin, hit.point, Color.red);

                // Instantiate the decal prefab according the hit normal
                EasyDecal.ProjectAt(DecalPrefab_A.gameObject, hit.collider.gameObject, hit.point, hit.normal);
            }
        }
	}
}

 

Copyright © 2020 by Sycoforge Technologies. All Rights Reserved.