I am making a game in 2d where u need to blow a balloon by holding your mouse the opposite direction u want it to go. My problem is that i have no idé for the code that is gonna blow the balloon away. For example if you holding the mouse under the Balloon the balloon is gonna move uppwards and if u hold it on the left it is gonna move to the right. Hope u understan and really want an quick answer. The code in C# plz
Create a C# script, copy and paste this (Make sure class name and script name are the same, so replace h_BalloonController to the script name) and attach it to your balloon. change mass and gravity multiplier in the Rigidbody component to around 0.1
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(CircleCollider2D))]
public class h_BalloonController : MonoBehaviour
{
#region Components
private Rigidbody2D rigidbody = null;
public Rigidbody2D Rigidbody
{
get
{
if (rigidbody == null)
{
rigidbody = GetComponent<Rigidbody2D>();
}
return rigidbody;
}
}
private Transform transform = null;
public Transform Transform
{
get
{
if (transform == null)
{
transform = GetComponent<Transform>();
}
return transform;
}
}
private CircleCollider2D collider = null;
private CircleCollider2D Collider
{
get
{
if (collider == null)
{
collider = GetComponent<CircleCollider2D>();
}
return collider;
}
}
#endregion
[SerializeField] private float blowPower = 1.0f;
[SerializeField] private float blowRange = 30.0f;
[SerializeField] private AnimationCurve blowFalloff = new AnimationCurve(new Keyframe(0.0f, 1.0f), new Keyframe(1.0f, 0.0f));
[SerializeField] private Camera camera = null;
private Vector2 mousePosition = Vector2.zero;
private bool blow = false;
private void Start()
{
if (camera == null) { camera = Camera.main; }
}
private void Update()
{
if (camera != null)
{
mousePosition = camera.ScreenToWorldPoint(Input.mousePosition);
blow = Input.GetButton("Fire1");
}
else
{
blow = false;
}
}
private void FixedUpdate()
{
if (blow)
{
Vector2 force = (Vector2)Transform.position;
force -= mousePosition;
if (force.magnitude > blowRange) { return; }
force = force.normalized * blowFalloff.Evaluate(force.magnitude / blowRange);
force *= blowPower;
Rigidbody.AddForce(force);
}
}
}