Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

Unity 2d

void FixedUpdate()
{
    //Use Velocity
	if (Input.GetKey(KeyCode.D))
        {
        	//add velocity to rigidbody 3 units along x axis and 0 units along y axis
            //Velocity is not affected by Gravity
            //Velocity i constant in every frame I.e Force=3
            //Velocity starts from the initial value stated which in this case is 3
            //rigidbody2d.velocity = new vector2(x,y);
            //x is sideways and y is upwards
            
            rb2d.velocity = new Vector2(3,0);
            
            
           //To gradually increase Velocity in each frame see the line of code below
           
           rb2d.velocity += new Vector2(3,0);
        }
        
	//OR Use Force
	if (Input.GetKey(KeyCode.D))
        {
        	//Gradually adds Force/velocity to rigidbody 4 units to the right along x axis
            //Force is affected by gravity and Drag
            //Force starts from 0 and increases gradually by 4 units per frame
            rb2d.AddForce (Vector2.right * 4);
        }
}
Source by medium.com #
 
PREVIOUS NEXT
Tagged: #Unity
ADD COMMENT
Topic
Name
2+1 =