Hello! I am very very new to game dev and I just have a quick q.
I am wanting the player to be able to drag an object (ball in this case) to launch it, however, I would like the dragging to stop at certain coordinates) Imagine a box around the ball. I want the maximum draw distance of the player to be able to pull back the ball to be around this box. This is also a 2d game and its a touch input. Heres my code so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using Cinemachine;
public class BallHandling : MonoBehaviour
{
[SerializeField] private Camera mainCamera;
private bool isDragging;
[SerializeField] public GameObject ballPrefab;
[SerializeField] private Rigidbody2D pivotPoint;
[SerializeField] private float respawnDelay;
[SerializeField] private float delayDuration;
[SerializeField] private BoxCollider2D deathZone;
private Rigidbody2D currentBallRigidBody;
private SpringJoint2D currentBallSpringJoint;
// Start is called before the first frame update
void Start()
{
SpawnBall();
}
// Update is called once per frame
void Update()
{
if (currentBallRigidBody == null)
{
return;
}
if (!Touchscreen.current.primaryTouch.press.isPressed)
{
if (isDragging)
{
LaunchBall();
}
isDragging = false;
//Return means, don't run anything in this method after this line
return;
}
isDragging = true;
//read the touch position
Vector2 touchPoistion = Touchscreen.current.primaryTouch.position.ReadValue();
//converting to world point
Vector2 worldPosition = mainCamera.ScreenToWorldPoint(touchPoistion);
//displaying the converted world position
//Debug.Log(worldPosition);
//Making to where the ball will go to where we touch
currentBallRigidBody.position = worldPosition;
//Setting the physics to not interfere
currentBallRigidBody.isKinematic = true;
Debug.Log(touchPoistion);
}
private void LaunchBall()
{
//Turning off physics
currentBallRigidBody.isKinematic = false;
currentBallRigidBody = null;
//Adding a delay
Invoke("DetachBall", delayDuration);
}
private void DetachBall()
{
//Detaching ball
currentBallSpringJoint.enabled = false;
currentBallSpringJoint = null;
}
public void SpawnBall()
{
//Spawning new ball
var ballInstance = Instantiate(ballPrefab, pivotPoint.position, Quaternion.identity);
//Grabbing those components
currentBallRigidBody = ballInstance.GetComponent<Rigidbody2D>();
currentBallSpringJoint = ballInstance.GetComponent<SpringJoint2D>();
//Attaching new ball to pivotpoint
currentBallSpringJoint.connectedBody = pivotPoint;
//Attaching camera to new ball
}
}