Unity C#与Raycast拍摄脚本
我正在Unity中创建一个2d头顶游戏。到目前为止,我已经能够让玩家以几乎正确的角度跟随鼠标(但是它仍然以一种奇怪的方式移动)。我还试图给玩家一个拍摄功能,从正确的角度(拍摄时直接从玩家顶部)拍摄光线。当我单击“使用此代码”时,不会发生任何事情。我已经为玩家、子弹和火力点设置了对象Unity C#与Raycast拍摄脚本,c#,unity3d,2d-games,raytracing,C#,Unity3d,2d Games,Raytracing,我正在Unity中创建一个2d头顶游戏。到目前为止,我已经能够让玩家以几乎正确的角度跟随鼠标(但是它仍然以一种奇怪的方式移动)。我还试图给玩家一个拍摄功能,从正确的角度(拍摄时直接从玩家顶部)拍摄光线。当我单击“使用此代码”时,不会发生任何事情。我已经为玩家、子弹和火力点设置了对象 public void Update() { if (FollowMouse || Input.GetMouseButton(0)) { _targ
public void Update()
{
if (FollowMouse || Input.GetMouseButton(0))
{
_target = Camera.ScreenToWorldPoint(Input.mousePosition);
_target.z = 0;
}
var delta = currentSpeed * Time.deltaTime;
if (ShipAccelerates)
{
delta *= Vector3.Distance(transform.position, _target);
}
angle = Mathf.Atan2(_target.y, _target.x) * Mathf.Rad2Deg;
transform.position = Vector3.MoveTowards(transform.position, _target, delta);
transform.rotation = Quaternion.Euler(0, 0, angle);
if ((Input.GetMouseButtonDown(0) || Input.GetKeyDown("space")) && Time.time > nextFire && numOfBullets > 0)
{
nextFire = Time.time + fireRate;
// Instantiate(bullet, firePoint.position, firePoint.rotation);
numOfBullets--;
// bullet.transform.position = Vector3.MoveTowards(bullet.transform.position, _target, bulletDelta);
shoot();
firePoint.position = _target;
}
if(Input.GetMouseButtonDown(1) && fuel > 0)
{
currentSpeed = zoomSpeed;
while(fuel > 0)
{
fuel--;
}
currentSpeed = ShipSpeed;
}
}
void Start()
{
currentSpeed = ShipSpeed;
}
void shoot()
{
Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 firePointPosition = new Vector2(firePoint.position.x, firePoint.position.y);
RaycastHit2D hit = Physics2D.Raycast(firePointPosition, mousePosition-firePointPosition, 100, notToHit);
Debug.DrawLine(firePointPosition, _target);
}
试试这个,它将从游戏对象所在的位置开始拍摄一条光线,并沿方向变换。向右移动距离为100,忽略“notToHit”。debug.drawRay将在显示光线的场景视图中显示一条红线(距离为1)。在一切正常后删除此项,因为它会减慢游戏速度
RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position,transform.right,100, notToHit);
if (hit.transform != null) {
Debug.Log ("You Hit: "hit.transform.gameObject.name);
}
Debug.DrawRay (gameObject.transform.position, transform.right, Color.red, 5);
我之所以使用transform.right而不是计算鼠标位置的角度,是因为你说玩家跟随鼠标(所以我假设玩家已经在看鼠标)。但是,如果这不是您想要的,您可以随时将其更改为您想要的方式。您正在调用
Physics2D.Raycast
但没有对结果执行任何操作?