Answers for "how to code gravity in unity"

C#
0

gravity script unity

// Keep in mind that this solution is for custom physics.
// The easy way to add gravity is to just slap a RigidBody component 
// on your objects.

using UnityEngine;

public class MyObject : MonoBehaviour
{
	public Vector3 speed;
	public float gravity = 9.8f;

	// Start() is called before the first frame
	void Start()
    {
    	speed = new Vector3(0f, 0f, 0f);
    }

	// FixedUpdate() is called at regular time intervals independent of frames
	void FixedUpdate()
	{
    	speed.Set(speed.x, speed.y - gravity * Time.fixedDeltaTime, speed.z);
        transform.position += speed;
	}
}
Posted by: Guest on April-29-2021
0

how to change gravity unity

// Four times as strong
Physics2D.gravity = new Vector2(0, Physics2D.gravity.y * 4); 

// Half the strength
Physics2D.gravity = new Vector2(0, Physics2D.gravity.y / 2);
Posted by: Guest on June-10-2021

C# Answers by Framework

Browse Popular Code Answers by Language