Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Transfering local hit coordinate to a variable script?

Discussion in 'Scripting' started by Ace_1999, Jul 15, 2014.

  1. Ace_1999

    Ace_1999

    Joined:
    Jun 11, 2014
    Posts:
    30
    I came across a very useful shader effect, but fully implementing it appears to require a script that would alter Material.SetVector() and Material.SetFloat().

    Is there a script that would record the collision vector and force of an object hitting a mesh which could be used to set the variables in the shader below?

    http://forums.revora.net/topic/87068-3d-localized-shield-flare-shader-star-trek-like-shields/

    It's a bit frustrating to find a shader that does exactly what I need but lacks a key component to implement it in a scene.
     
  2. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    OnCollisionEnter method could be used to detect point of hit - http://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html and it's Collision argiment could be used to get relativeVelocity value - that can be used to detect vector of hit (I'm not sure, but hope it's true) http://docs.unity3d.com/ScriptReference/Collision-relativeVelocity.html
     
  3. AlucardJay

    AlucardJay

    Joined:
    May 28, 2012
    Posts:
    328
    As Patico has stated.

    To answer alter Material.SetVector() and Material.SetFloat() : http://docs.unity3d.com/ScriptReference/Material.SetVector.html

    As the shader requires a Vector4 in local space, use Transform.InverseTransformPoint to convert a world position to a local position. Then construct a temporary Vector4. Something like this :

    Code (csharp):
    1. Vector3 localPoint = transform.InverseTransformPoint( point );
    2. Vector4 lp = new Vector4( localPoint.x, localPoint.y, localPoint.z, 0 );
    3. renderer.material.SetVector( "_Position", lp );
     
  4. Ace_1999

    Ace_1999

    Joined:
    Jun 11, 2014
    Posts:
    30
    Thanks for the comments. This is what I have so far, and it's giving an error that 'point' does not exist in the current context. Which I assume has something to do with declaring variables?

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class ExampleClass : MonoBehaviour {
    6.     public Transform Shield_Frigate;
    7.     void OnCollisionEnter(Collision collision) {
    8.         Vector3 localPoint = transform.InverseTransformPoint( point );
    9.         Vector4 lp = new Vector4( localPoint.x, localPoint.y, localPoint.z, 0 );
    10.         renderer.material.SetVector( "_Position", lp );
    11.     }
    12. }