I'm currently working on a 3D game project where one of the core game mechanics of the game is to drag your mouse and release to make it go the other way. You could think of this as how you would play Angry Birds, where you have to drag your character and release to go the other way.
In this image I tried to explain what's wrong in my code. I want to click on the ball and drag it on blue line, and then when its released I want the ball to go on the red line and hit the capsule on its way. But instead the ball is following the green line. Like it has no depth.
The following is my code: DragAndShoot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(Collider))]
public class DragAndShoot : MonoBehaviour
{
private Vector3 mousePressDownPos;
private Vector3 mouseReleasePos;
private Rigidbody rb;
private bool isShoot;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update() {
//if isShoot is true, then the ball is already shot. Wait for it to stop moving.
//after it has stopped moving, we can shoot again.
if(isShoot && rb.velocity.magnitude < 0.1f)
{
isShoot = false;
}
}
private void OnMouseDown()
{
mousePressDownPos = Input.mousePosition;
}
private void OnMouseUp()
{
mouseReleasePos = Input.mousePosition;
Shoot(mouseReleasePos-mousePressDownPos);
}
private float forceMultiplier = 3;
void Shoot(Vector3 Force)
{
if(isShoot)
return;
rb.AddForce(-Force * forceMultiplier);
isShoot = true;
}
}
I tried using ScreenToWorldPoint() function, however the point is bugged and whenever I click on an object it disappears. I'm open to any suggestions as to find out what's wrong in my code or what should I add in order to fix this.
Okay, after looking back at my code, I figured I was having problems on these 3 methods, so I updated them:
private void OnMouseDown()
{
mousePressDownPos = new Vector3(Input.mousePosition.x, Input.mousePosition.z, Input.mousePosition.y);
}
private void OnMouseUp()
{
mouseReleasePos = new Vector3(Input.mousePosition.x, Input.mousePosition.z, Input.mousePosition.y);
Debug.Log("mouseReleasePos: " + mouseReleasePos);
Debug.Log("mousePressDownPos: " + mousePressDownPos);
Vector3 force = mouseReleasePos - mousePressDownPos;
Debug.Log("force: " + force);
Shoot(force);
}
void Shoot(Vector3 force)
{
if(isShoot)
return;
Vector3 forceVector = new Vector3(force.x, force.y, force.z);
forceVector = -forceVector;
Debug.Log("forceVector: " + forceVector);
rb.AddForce(forceVector * forceMultiplier);
isShoot = true;
}
In addition to this, unity dimensions has to stay like this, otherwise code won't work properly.