There are two methods to make object move in unity:
- By changing its Transform (Position).
- By adding Force by using AddForce() method.
In this blog I have mentioned, how we can make object move by adding force.
Force and Velocity both are component of Physics. So, to make our gameobject come under influence of Physics we must attach a rigid body to it and then we can code it to move by adding force in different direction.
Below is the script for your reference.
using UnityEngine;
using System.Collections;
public class BallScript : MonoBehaviour
{
void Update ()
{
if (Input.GetKey (KeyCode.UpArrow))
{
this.gameObject.rigidbody.AddForce(0,0,10,ForceMode.Acceleration);
}
if (Input.GetKey (KeyCode.DownArrow))
{
this.gameObject.rigidbody.AddForce(0,0,-10,ForceMode.Acceleration);
}
if (Input.GetKey (KeyCode.LeftArrow))
{
this.gameObject.rigidbody.AddForce(-10,0,0,ForceMode.Acceleration);
}
if (Input.GetKey (KeyCode.RightArrow))
{
this.gameObject.rigidbody.AddForce(10,0,0,ForceMode.Acceleration);
}
if (Input.GetKey (KeyCode.M))
{
this.gameObject.rigidbody.AddForce(0,20,0,ForceMode.Acceleration);
}
}
}
AddForce() method have 4 variants and we can use any of them to make our object move.
public void AddForce(vector3 force);
public void AddForce(vector3 force , ForceMode mode);
public void AddForce(float x, float y, float z);
public void AddForce(float x, float y, float z, vector3 force);
0 Comment(s)