我正在Unity制作2D游戏,我无法在游戏中向鼠标位置击球!当用户指示鼠标朝向击球时,它应该像通常的水池游戏一样击中它。
这是我的C#代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class whiteBall : MonoBehaviour {
Rigidbody2D rb;
int speed;
public GameObject ball;
public GameObject cue;
Vector3 mousePos;
void Start()
{
rb = GetComponent<Rigidbody2D>();
speed = 10;
}
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "pockets")
{
Debug.Log("Game collision with pockets");
}
}
void Update()
{
hitBall();
mousePos = Input.mousePosition;
// mouse move cordianates
Vector3 objectPos = Camera.main.WorldToScreenPoint(transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0,0,angle));
}
public void hitBall()
{
if(Input.GetMouseButtonUp(0))
{
Vector2 newPos = new Vector2(Mathf.Abs(mousePos.x), Mathf.Abs(mousePos.y));
rb.AddForce(newPos * 20 * Time.deltaTime, ForceMode2D.Impulse);
Debug.Log(newPos);
}
}
}