ФИЗИКА - Форум
  • Страница 1 из 1
  • 1
Модератор форума: terex  
Форум » игростроение » УРОКИ UNITY 3D » ФИЗИКА (физические скрипты)
ФИЗИКА
terexДата: Среда, 23.03.2011, 21:53 | Сообщение # 1
Zzz
Группа: Администраторы
Сообщений: 71
Награды: 1
Репутация: 32767
Статус: Offline
скрипт SimpleRotation позволяет вращать объект вокруг своей оси

Code
#pragma strict
#pragma implicit
#pragma downcast

class SimpleRotation extends MonoBehaviour
{
  public var desiredAxis : DesiredAxis;
  public var visualSlowSpeed : float = 0.5;
  public var framePerVisualRotation : int = 4;
   
  private var t : Transform;
  private var axis : Vector3;
   
  function Start()
  {
   t = transform;
    
   axis = new Vector3(1, 0, 0);
    
   switch(desiredAxis)
   {
    case DesiredAxis.Y:
     axis = new Vector3(0, 1, 0);
     break;
    case DesiredAxis.Z:
     axis = new Vector3(0, 0, 1);
     break;
   }
  }
   
  function Update()
  {
         if(GameManager.pause) return;
    
   t.Rotate(axis * (visualSlowSpeed * 360f * Time.deltaTime + 360f / framePerVisualRotation));
  }
}

enum DesiredAxis
{
  X,
  Y,
  Z
}
 
terexДата: Среда, 23.03.2011, 23:36 | Сообщение # 2
Zzz
Группа: Администраторы
Сообщений: 71
Награды: 1
Репутация: 32767
Статус: Offline
длительность жизни объекта
Code
var lifeTime = 1.0;

function Awake ()
{
   Destroy (gameObject, lifeTime);
}
 
terexДата: Вторник, 29.03.2011, 20:50 | Сообщение # 3
Zzz
Группа: Администраторы
Сообщений: 71
Награды: 1
Репутация: 32767
Статус: Offline
скрипт DragRigidbodyShadow.
зажатием кнопки мыши умеет перемещать объекты (есть возможность настройки скрипта) (применяет объектам центр цент тяжести, чтобы не добавлять каждому объекту этот скрипт, просто добавте скрипт на камеру)

Code
var spring = 50.0;
var damper = 5.0;
var drag = 10.0;
var angularDrag = 5.0;
var distance = 0.2;
var pushForce = 0.2;
var attachToCenterOfMass = false;

var highlightMaterial : Material;
private var highlightObject : GameObject;

private var springJoint : SpringJoint;

function Update()
{
   var mainCamera = FindCamera();
     
   highlightObject = null;
   if( springJoint != null && springJoint.connectedBody != null )
   {
    highlightObject = springJoint.connectedBody.gameObject;
   }
   else
   {
    // Сталкновение с объектами   
    var hitt : RaycastHit;
    if( Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition),  hitt, 100 ) ) {
     if( hitt.rigidbody && !hitt.rigidbody.isKinematic ) {
      highlightObject = hitt.rigidbody.gameObject;
     }
    }
   }
     
      
   // Убедитесь, что пользователь зажал кнопку мыши вниз
   if (!Input.GetMouseButtonDown (0))
    return;

      
   //  Сталкновение с объектами   
   var hit : RaycastHit;
   if (!Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition),  hit, 100)) {
    return;
   }
   // жмем на rigidbody у которого нет кинематики   
   if (!hit.rigidbody || hit.rigidbody.isKinematic) {
    return;
   }
     
   if (!springJoint)
   {
    var go = new GameObject("Rigidbody dragger");
    body = go.AddComponent ("Rigidbody");
    springJoint = go.AddComponent ("SpringJoint");
    body.isKinematic = true;
   }
     
   springJoint.transform.position = hit.point;
   if (attachToCenterOfMass)
   {
    var anchor = transform.TransformDirection(hit.rigidbody.centerOfMass) + hit.rigidbody.transform.position;
    anchor = springJoint.transform.InverseTransformPoint(anchor);
    springJoint.anchor = anchor;
   }
   else
   {
    springJoint.anchor = Vector3.zero;
   }
     
   springJoint.spring = spring;
   springJoint.damper = damper;
   springJoint.maxDistance = distance;
   springJoint.connectedBody = hit.rigidbody;
     
   DragObject(hit.distance, hit.point, mainCamera.ScreenPointToRay(Input.mousePosition).direction);
}

function DragObject (distance : float, hitpoint : Vector3, dir : Vector3)
{
   var startTime = Time.time;
   var mousePos = Input.mousePosition;
     
     
   var oldDrag = springJoint.connectedBody.drag;
   var oldAngularDrag = springJoint.connectedBody.angularDrag;
   springJoint.connectedBody.drag = drag;
   springJoint.connectedBody.angularDrag = angularDrag;
   var mainCamera = FindCamera();
   while (Input.GetMouseButton (0))
   {
    var ray = mainCamera.ScreenPointToRay (Input.mousePosition);
    springJoint.transform.position = ray.GetPoint(distance);
    yield;
   }
     
   if (Mathf.Abs(mousePos.x - Input.mousePosition.x) <= 2 && Mathf.Abs(mousePos.y - Input.mousePosition.y) <= 2 && Time.time - startTime < .2 && springJoint.connectedBody)
   {
    dir.y = 0;
    dir.Normalize();
    springJoint.connectedBody.AddForceAtPosition(dir * pushForce, hitpoint, ForceMode.VelocityChange);
    ToggleLight( springJoint.connectedBody.gameObject );
   }   
     
     
   if (springJoint.connectedBody)
   {
    springJoint.connectedBody.drag = oldDrag;
    springJoint.connectedBody.angularDrag = oldAngularDrag;
    springJoint.connectedBody = null;
   }
}

static function ToggleLight( go : GameObject )
{    
   var theLight : Light = go.GetComponentInChildren(Light);
   if( !theLight )
    return;
      
   theLight.enabled = !theLight.enabled;
   var illumOn = theLight.enabled;
   var renderers = go.GetComponentsInChildren(MeshRenderer);
   for( var r : MeshRenderer in renderers )
   {
    if( r.gameObject.layer == 1 )
    {
     r.material.shader = Shader.Find(illumOn ? "Self-Illumin/Diffuse" : "Diffuse");
    }
   }
}

function FindCamera ()
{
   if (camera)
    return camera;
   else
    return Camera.main;
}

function OnPostRender()
{
   if( highlightObject == null )
    return;
      
   var go = highlightObject;
   highlightMaterial.SetPass( 0 );
   var meshes = go.GetComponentsInChildren(MeshFilter);
   for( var m : MeshFilter in meshes )
   {
    Graphics.DrawMeshNow( m.sharedMesh, m.transform.position, m.transform.rotation );
   }
}
 
terexДата: Вторник, 29.03.2011, 21:15 | Сообщение # 4
Zzz
Группа: Администраторы
Сообщений: 71
Награды: 1
Репутация: 32767
Статус: Offline
скрипт ShadowUI выводит на экран все источники освещения

и имеет возможность управлять ими
(скрипт взаимодействует с DragRigidbodyShadow, в таком случае появляется возможность управлять освещением курсором мыши)

Code
var lights : Light[];

function OnGUI()
{
  GUILayout.BeginArea( Rect( 2, Screen.height-130, 150, 128 ), "Settings", GUI.skin.window  );
  for( var l in lights )
  {
   l.enabled = GUILayout.Toggle( l.enabled, l.name );
  }
  GUILayout.EndArea();
}
 
terexДата: Вторник, 29.03.2011, 21:28 | Сообщение # 5
Zzz
Группа: Администраторы
Сообщений: 71
Награды: 1
Репутация: 32767
Статус: Offline
скрипт DraggCollor, в отличии от скрипта DragRigidbodyShadow, просто перемещает объект, без всяких настроек и центра тяжести, при этом можно выбрать любой цвет при наведении на объект

Code
var mouseOverColor = Color.blue;
private var originalColor : Color;
function Start () {
  originalColor = renderer.sharedMaterial.color;
}
function OnMouseEnter () {
  renderer.material.color = mouseOverColor;
}

function OnMouseExit () {
  renderer.material.color = originalColor;
}

function OnMouseDown () {
  var screenSpace = Camera.main.WorldToScreenPoint(transform.position);
  var offset = transform.position - Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
  while (Input.GetMouseButton(0))
  {
   var curScreenSpace = Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
   var curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
   transform.position = curPosition;
   yield;
  }
}
 
terexДата: Среда, 30.03.2011, 07:55 | Сообщение # 6
Zzz
Группа: Администраторы
Сообщений: 71
Награды: 1
Репутация: 32767
Статус: Offline
скрипт C# MirrorReflection позволяет делать с материала зеркало (идет вместе с шейдером MirrorReflection)
Code
using UnityEngine;
using System.Collections;

// This is in fact just the Water script from Pro Standard Assets,
// just with refraction stuff removed.

[ExecuteInEditMode] // Make mirror live-update even when not in play mode
public class MirrorReflection : MonoBehaviour
{
     public bool m_DisablePixelLights = true;
     public int m_TextureSize = 256;
     public float m_ClipPlaneOffset = 0.07f;
      
     public LayerMask m_ReflectLayers = -1;
          
     private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table
      
     private RenderTexture m_ReflectionTexture = null;
     private int m_OldReflectionTextureSize = 0;
      
     private static bool s_InsideRendering = false;

     // This is called when it's known that the object will be rendered by some
     // camera. We render reflections and do other updates here.
     // Because the script executes in edit mode, reflections for the scene view
     // camera will just work!
     public void OnWillRenderObject()
     {
         if( !enabled || !renderer || !renderer.sharedMaterial || !renderer.enabled )
             return;
              
         Camera cam = Camera.current;
         if( !cam )
             return;
      
         // Safeguard from recursive reflections.         
         if( s_InsideRendering )
             return;
         s_InsideRendering = true;
          
         Camera reflectionCamera;
         CreateMirrorObjects( cam, out reflectionCamera );
          
         // find out the reflection plane: position and normal in world space
         Vector3 pos = transform.position;
         Vector3 normal = transform.up;
          
         // Optionally disable pixel lights for reflection
         int oldPixelLightCount = QualitySettings.pixelLightCount;
         if( m_DisablePixelLights )
             QualitySettings.pixelLightCount = 0;
          
         UpdateCameraModes( cam, reflectionCamera );
          
         // Render reflection
         // Reflect camera around reflection plane
         float d = -Vector3.Dot (normal, pos) - m_ClipPlaneOffset;
         Vector4 reflectionPlane = new Vector4 (normal.x, normal.y, normal.z, d);
      
         Matrix4x4 reflection = Matrix4x4.zero;
         CalculateReflectionMatrix (ref reflection, reflectionPlane);
         Vector3 oldpos = cam.transform.position;
         Vector3 newpos = reflection.MultiplyPoint( oldpos );
         reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
      
         // Setup oblique projection matrix so that near plane is our reflection
         // plane. This way we clip everything below/above it for free.
         Vector4 clipPlane = CameraSpacePlane( reflectionCamera, pos, normal, 1.0f );
         Matrix4x4 projection = cam.projectionMatrix;
         CalculateObliqueMatrix (ref projection, clipPlane);
         reflectionCamera.projectionMatrix = projection;
          
         reflectionCamera.cullingMask = ~(1<<4) & m_ReflectLayers.value; // never render water layer
         reflectionCamera.targetTexture = m_ReflectionTexture;
         GL.SetRevertBackfacing (true);
         reflectionCamera.transform.position = newpos;
         Vector3 euler = cam.transform.eulerAngles;
         reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
         reflectionCamera.Render();
         reflectionCamera.transform.position = oldpos;
         GL.SetRevertBackfacing (false);
         Material[] materials = renderer.sharedMaterials;
         foreach( Material mat in materials ) {
             if( mat.HasProperty("_ReflectionTex") )
                 mat.SetTexture( "_ReflectionTex", m_ReflectionTexture );
         }
          
         // Set matrix on the shader that transforms UVs from object space into screen
         // space. We want to just project reflection texture on screen.
         Matrix4x4 scaleOffset = Matrix4x4.TRS(
             new Vector3(0.5f,0.5f,0.5f), Quaternion.identity, new Vector3(0.5f,0.5f,0.5f) );
         Vector3 scale = transform.lossyScale;
         Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale( new Vector3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z) );
         mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;
         foreach( Material mat in materials ) {
             mat.SetMatrix( "_ProjMatrix", mtx );
         }
          
         // Restore pixel light count
         if( m_DisablePixelLights )
             QualitySettings.pixelLightCount = oldPixelLightCount;
          
         s_InsideRendering = false;
     }
      
      
     // Cleanup all the objects we possibly have created
     void OnDisable()
     {
         if( m_ReflectionTexture ) {
             DestroyImmediate( m_ReflectionTexture );
             m_ReflectionTexture = null;
         }
         foreach( DictionaryEntry kvp in m_ReflectionCameras )
             DestroyImmediate( ((Camera)kvp.Value).gameObject );
         m_ReflectionCameras.Clear();
     }
      
      
     private void UpdateCameraModes( Camera src, Camera dest )
     {
         if( dest == null )
             return;
         // set camera to clear the same way as current camera
         dest.clearFlags = src.clearFlags;
         dest.backgroundColor = src.backgroundColor;         
         if( src.clearFlags == CameraClearFlags.Skybox )
         {
             Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
             Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
             if( !sky || !sky.material )
             {
                 mysky.enabled = false;
             }
             else
             {
                 mysky.enabled = true;
                 mysky.material = sky.material;
             }
         }
         // update other values to match current camera.
         // even if we are supplying custom camera&projection matrices,
         // some of values are used elsewhere (e.g. skybox uses far plane)
         dest.farClipPlane = src.farClipPlane;
         dest.nearClipPlane = src.nearClipPlane;
         dest.orthographic = src.orthographic;
         dest.fieldOfView = src.fieldOfView;
         dest.aspect = src.aspect;
         dest.orthographicSize = src.orthographicSize;
     }
      
     // On-demand create any objects we need
     private void CreateMirrorObjects( Camera currentCamera, out Camera reflectionCamera )
     {
         reflectionCamera = null;
          
         // Reflection render texture
         if( !m_ReflectionTexture || m_OldReflectionTextureSize != m_TextureSize )
         {
             if( m_ReflectionTexture )
                 DestroyImmediate( m_ReflectionTexture );
             m_ReflectionTexture = new RenderTexture( m_TextureSize, m_TextureSize, 16 );
             m_ReflectionTexture.name = "__MirrorReflection" + GetInstanceID();
             m_ReflectionTexture.isPowerOfTwo = true;
             m_ReflectionTexture.hideFlags = HideFlags.DontSave;
             m_OldReflectionTextureSize = m_TextureSize;
         }
          
         // Camera for reflection
         reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
         if( !reflectionCamera ) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
         {
             GameObject go = new GameObject( "Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox) );
             reflectionCamera = go.camera;
             reflectionCamera.enabled = false;
             reflectionCamera.transform.position = transform.position;
             reflectionCamera.transform.rotation = transform.rotation;
             reflectionCamera.gameObject.AddComponent("FlareLayer");
             go.hideFlags = HideFlags.HideAndDontSave;
             m_ReflectionCameras[currentCamera] = reflectionCamera;
         }         
     }
      
     // Extended sign: returns -1, 0 or 1 based on sign of a
     private static float sgn(float a)
     {
         if (a > 0.0f) return 1.0f;
         if (a < 0.0f) return -1.0f;
         return 0.0f;
     }
      
     // Given position/normal of the plane, calculates plane in camera space.
     private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
     {
         Vector3 offsetPos = pos + normal * m_ClipPlaneOffset;
         Matrix4x4 m = cam.worldToCameraMatrix;
         Vector3 cpos = m.MultiplyPoint( offsetPos );
         Vector3 cnormal = m.MultiplyVector( normal ).normalized * sideSign;
         return new Vector4( cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos,cnormal) );
     }
      
     // Adjusts the given projection matrix so that near plane is the given clipPlane
     // clipPlane is given in camera space. See article in Game Programming Gems 5.
     private static void CalculateObliqueMatrix (ref Matrix4x4 projection, Vector4 clipPlane)
     {
         Vector4 q = projection.inverse * new Vector4(
             sgn(clipPlane.x),
             sgn(clipPlane.y),
             1.0f,
             1.0f
         );
         Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
         // third row = clip plane - fourth row
         projection[2] = c.x - projection[3];
         projection[6] = c.y - projection[7];
         projection[10] = c.z - projection[11];
         projection[14] = c.w - projection[15];
     }

     // Calculates reflection matrix around the given plane
     private static void CalculateReflectionMatrix (ref Matrix4x4 reflectionMat, Vector4 plane)
     {
         reflectionMat.m00 = (1F - 2F*plane[0]*plane[0]);
         reflectionMat.m01 = (   - 2F*plane[0]*plane[1]);
         reflectionMat.m02 = (   - 2F*plane[0]*plane[2]);
         reflectionMat.m03 = (   - 2F*plane[3]*plane[0]);

         reflectionMat.m10 = (   - 2F*plane[1]*plane[0]);
         reflectionMat.m11 = (1F - 2F*plane[1]*plane[1]);
         reflectionMat.m12 = (   - 2F*plane[1]*plane[2]);
         reflectionMat.m13 = (   - 2F*plane[3]*plane[1]);
      
         reflectionMat.m20 = (   - 2F*plane[2]*plane[0]);
         reflectionMat.m21 = (   - 2F*plane[2]*plane[1]);
         reflectionMat.m22 = (1F - 2F*plane[2]*plane[2]);
         reflectionMat.m23 = (   - 2F*plane[3]*plane[2]);

         reflectionMat.m30 = 0F;
         reflectionMat.m31 = 0F;
         reflectionMat.m32 = 0F;
         reflectionMat.m33 = 1F;
     }
}
 
terexДата: Пятница, 01.04.2011, 05:21 | Сообщение # 7
Zzz
Группа: Администраторы
Сообщений: 71
Награды: 1
Репутация: 32767
Статус: Offline
скрипт HeightmapGenerator с помощью которого возможно из текстуры наносить рельеф на поверхность объектов

Code
var heightMap : Texture2D;
var material : Material;
var size = Vector3(200, 30, 200);

function Start ()
{
  GenerateHeightmap();
}

function GenerateHeightmap ()
{
  // Create the game object containing the renderer
  gameObject.AddComponent(MeshFilter);
  gameObject.AddComponent("MeshRenderer");
  if (material)
   renderer.material = material;
  else
   renderer.material.color = Color.white;

  // Retrieve a mesh instance
  var mesh : Mesh = GetComponent(MeshFilter).mesh;

  var width : int = Mathf.Min(heightMap.width, 255);
  var height : int = Mathf.Min(heightMap.height, 255);
  var y = 0;
  var x = 0;

  // Build vertices and UVs
  var vertices = new Vector3[height * width];
  var uv = new Vector2[height * width];
  var tangents = new Vector4[height * width];
   
  var uvScale = Vector2 (1.0 / (width - 1), 1.0 / (height - 1));
  var sizeScale = Vector3 (size.x / (width - 1), size.y, size.z / (height - 1));
   
  for (y=0;y<height;y++)
  {
   for (x=0;x<width;x++)
   {
    var pixelHeight = heightMap.GetPixel(x, y).grayscale;
    var vertex = Vector3 (x, pixelHeight, y);
    vertices[y*width + x] = Vector3.Scale(sizeScale, vertex);
    uv[y*width + x] = Vector2.Scale(Vector2 (x, y), uvScale);

    // Calculate tangent vector: a vector that goes from previous vertex
    // to next along X direction. We need tangents if we intend to
    // use bumpmap shaders on the mesh.
    var vertexL = Vector3( x-1, heightMap.GetPixel(x-1, y).grayscale, y );
    var vertexR = Vector3( x+1, heightMap.GetPixel(x+1, y).grayscale, y );
    var tan = Vector3.Scale( sizeScale, vertexR - vertexL ).normalized;
    tangents[y*width + x] = Vector4( tan.x, tan.y, tan.z, -1.0 );
   }
  }
   
  // Assign them to the mesh
  mesh.vertices = vertices;
  mesh.uv = uv;

  // Build triangle indices: 3 indices into vertex array for each triangle
  var triangles = new int[(height - 1) * (width - 1) * 6];
  var index = 0;
  for (y=0;y<height-1;y++)
  {
   for (x=0;x<width-1;x++)
   {
    // For each grid cell output two triangles
    triangles[index++] = (y     * width) + x;
    triangles[index++] = ((y+1) * width) + x;
    triangles[index++] = (y     * width) + x + 1;

    triangles[index++] = ((y+1) * width) + x;
    triangles[index++] = ((y+1) * width) + x + 1;
    triangles[index++] = (y     * width) + x + 1;
   }
  }
  // And assign them to the mesh
  mesh.triangles = triangles;
    
  // Auto-calculate vertex normals from the mesh
  mesh.RecalculateNormals();
   
  // Assign tangents after recalculating normals
  mesh.tangents = tangents;
}
 
terexДата: Пятница, 01.04.2011, 05:41 | Сообщение # 8
Zzz
Группа: Администраторы
Сообщений: 71
Награды: 1
Репутация: 32767
Статус: Offline
скрипт PaintVertices рисует рельефом на объектах

Code
var radius = 1.0;
var pull = 10.0;
private var unappliedMesh : MeshFilter;

enum FallOff { Gauss, Linear, Needle }
var fallOff = FallOff.Gauss;

static function LinearFalloff (distance : float , inRadius : float) {
  return Mathf.Clamp01(1.0 - distance / inRadius);
}

static function GaussFalloff (distance : float , inRadius : float) {
  return Mathf.Clamp01 (Mathf.Pow (360.0, -Mathf.Pow (distance / inRadius, 2.5) - 0.01));
}

function NeedleFalloff (dist : float, inRadius : float)
{
  return -(dist*dist) / (inRadius * inRadius) + 1.0;
}

function DeformMesh (mesh : Mesh, position : Vector3, power : float, inRadius : float)
{
  var vertices = mesh.vertices;
  var normals = mesh.normals;
  var sqrRadius = inRadius * inRadius;
   
  // Calculate averaged normal of all surrounding vertices  
  var averageNormal = Vector3.zero;
  for (var i=0;i<vertices.length;i++)
  {
   var sqrMagnitude = (vertices[i] - position).sqrMagnitude;
   // Early out if too far away
   if (sqrMagnitude > sqrRadius)
    continue;

   var distance = Mathf.Sqrt(sqrMagnitude);
   var falloff = LinearFalloff(distance, inRadius);
   averageNormal += falloff * normals[i];
  }
  averageNormal = averageNormal.normalized;
   
  // Deform vertices along averaged normal
  for (i=0;i<vertices.length;i++)
  {
   sqrMagnitude = (vertices[i] - position).sqrMagnitude;
   // Early out if too far away
   if (sqrMagnitude > sqrRadius)
    continue;

   distance = Mathf.Sqrt(sqrMagnitude);
   switch (fallOff)
   {
    case FallOff.Gauss:
     falloff = GaussFalloff(distance, inRadius);
     break;
    case FallOff.Needle:
     falloff = NeedleFalloff(distance, inRadius);
     break;
    default:
     falloff = LinearFalloff(distance, inRadius);
     break;
   }
    
   vertices[i] += averageNormal * falloff * power;
  }
   
  mesh.vertices = vertices;
  mesh.RecalculateNormals();
  mesh.RecalculateBounds();
}

function Update () {

  // When no button is pressed we update the mesh collider
  if (!Input.GetMouseButton (0))
  {
   // Apply collision mesh when we let go of button
   ApplyMeshCollider();
   return;
  }
    
    
  // Did we hit the surface?
  var hit : RaycastHit;
  var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  if (Physics.Raycast (ray, hit))
  {
   var filter : MeshFilter = hit.collider.GetComponent(MeshFilter);
   if (filter)
   {
    // Don't update mesh collider every frame since physX
    // does some heavy processing to optimize the collision mesh.
    // So this is not fast enough for real time updating every frame
    if (filter != unappliedMesh)
    {
     ApplyMeshCollider();
     unappliedMesh = filter;
    }
     
    // Deform mesh
    var relativePoint = filter.transform.InverseTransformPoint(hit.point);
    DeformMesh(filter.mesh, relativePoint, pull * Time.deltaTime, radius);
   }
  }
}

function ApplyMeshCollider () {
  if (unappliedMesh && unappliedMesh.GetComponent(MeshCollider)) {
   unappliedMesh.GetComponent(MeshCollider).mesh = unappliedMesh.mesh;
  }
  unappliedMesh = null;
}
 
terexДата: Пятница, 08.04.2011, 17:18 | Сообщение # 9
Zzz
Группа: Администраторы
Сообщений: 71
Награды: 1
Репутация: 32767
Статус: Offline
скрипт AnimationLoop позволяет повторять анимацию
Code
function Start ()
{
  animation.wrapMode = WrapMode.Loop;

}
 
Форум » игростроение » УРОКИ UNITY 3D » ФИЗИКА (физические скрипты)
  • Страница 1 из 1
  • 1
Поиск:
 Сайт временно находится в стадии разработки, приношу свои извинения за не удобства
 
 This site is temporarily under construction, I apologize for the convenience of not