using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class CastBallTutorial : MonoBehaviour
{
public float BallPositionCameraY = -1f;
public float BallPositionCameraZ = 0;
public GameObject prefabToInstantiate;
public float CastSpeed = 55;
public float BallCurve = 3;
public float ScreenHeight;
private void Awake()
{
ScreenHeight = (Screen.height / 2) / (BallCurve);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (!EventSystem.current.IsPointerOverGameObject())
{
Ray mouseRay = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y + ScreenHeight, 0));
GameObject newGameObject = (GameObject)Instantiate(prefabToInstantiate, new Vector3(mouseRay.origin.x, mouseRay.origin.y + BallPositionCameraY, mouseRay.origin.z - BallPositionCameraZ), Quaternion.identity);
Rigidbody rb = newGameObject.GetComponent<Rigidbody>();
if (rb != null)
{
Vector3 mouse = Input.mousePosition;
Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(new Vector3(mouse.x, mouse.y, newGameObject.transform.position.y));
Vector3 forward = mouseWorld - newGameObject.transform.position;
newGameObject.transform.rotation = Quaternion.LookRotation(forward, Vector3.up);
rb.velocity = mouseRay.direction * CastSpeed;
}
}
}
}
}
}
So i have this code that shoots an object and give it a litle rotation based on were on screen you click.
So if you have a cube and throw it by clicking on the right side of screen this object will rotate to look like its been thrown from the middle screen to the right, same works with left.
Problem is it doesnt work on low frames per second and on higher frames it also only work sometimes.
Can someone help me make the code beter please so it will work, thx.