ConstantVelocity

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
m (Text replace - "</javascript>" to "</syntaxhighlight>")
(Updated code)
 
Line 2: Line 2:
 
[[Category: C Sharp]]
 
[[Category: C Sharp]]
 
[[Category: ReallySimpleScripts]]
 
[[Category: ReallySimpleScripts]]
 
Author: Opless
 
 
 
== Description ==
 
== Description ==
  
 
+
Useful for things like missiles, bullets, etc. You can also alternatively just attach the built-in [https://docs.unity3d.com/Manual/class-ConstantForce.html ConstantForce] component to a GameObject.
Useful for missiles, grenades, etc
+
  
 
== CSharp - ConstantVelocity.cs ==
 
== CSharp - ConstantVelocity.cs ==
Line 14: Line 10:
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
 
using UnityEngine;
 
using UnityEngine;
using System.Collections;
 
  
public class ConstantVelocity : MonoBehaviour {
+
[RequireComponent (typeof (Rigidbody))]
 +
public class ConstantVelocity : MonoBehaviour
 +
{
 +
    public Vector3 direction = Vector3.forward;
  
public Vector3  direction      = Vector3.forward;
+
    private Rigidbody m_Rigidbody;
 +
    private Transform m_Transform;
  
// Use this for initialization
 
void Start ()
 
{
 
}
 
 
// Update is called once per frame
 
void Update ()
 
{
 
rigidbody.velocity =  transform.rotation * direction;
 
}
 
}
 
  
</syntaxhighlight>
+
    private void Awake ()
 +
    {
 +
        // Optimization - Cache component references.
 +
        m_Transform = GetComponent<Transform> ();
 +
        m_Rigidbody = GetComponent<Rigidbody> ();
 +
    }
  
== Javascript - ConstantVelocity.js ==
 
  
<syntaxhighlight lang="javascript">
+
     private void FixedUpdate ()
     var direction : Vector3 = Vector3.forward;
+
 
+
    function Update ()
+
 
     {
 
     {
         rigidbody.velocity = transform.rotation * direction;
+
         m_Rigidbody.velocity = m_Transform.rotation * direction;
 
     }
 
     }
 +
}
 +
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 15:41, 6 September 2018

[edit] Description

Useful for things like missiles, bullets, etc. You can also alternatively just attach the built-in ConstantForce component to a GameObject.

[edit] CSharp - ConstantVelocity.cs

using UnityEngine;
 
[RequireComponent (typeof (Rigidbody))]
public class ConstantVelocity : MonoBehaviour
{
    public Vector3 direction = Vector3.forward;
 
    private Rigidbody m_Rigidbody;
    private Transform m_Transform;
 
 
    private void Awake ()
    {
        // Optimization - Cache component references.
        m_Transform = GetComponent<Transform> ();
        m_Rigidbody = GetComponent<Rigidbody> ();
    }
 
 
    private void FixedUpdate ()
    {
        m_Rigidbody.velocity = m_Transform.rotation * direction;
    }
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox