gpt4 book ai didi

c# - Unity3d,在鼠标位置射击

转载 作者:行者123 更新时间:2023-12-04 16:09:36 25 4
gpt4 key购买 nike

我正在创建一个简单的街机游戏,但是我在射击时遇到了问题。玩家将有此 View 。 enter image description here我希望玩家从玩家角色的炮塔在鼠标位置射击。

这是我的代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class gunController : MonoBehaviour {

public float speed = 3f;
public float fireRate = 3f;
public float force = 10f;
public GameObject bulletPrefab;
public GameObject gunEnd;

private GameObject bullet;
private Camera mainCam;
private float distance = 50f;
private Vector3 mousePos;
private bulletController bc;
private bool canShoot = true;
private Vector3 aim;

void Start () {
mainCam = GameObject.Find ("Main Camera").GetComponent<Camera> ();
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
}

// Update is called once per frame
void Update () {
//Get mouse position. You need to call this every frame not just in start
mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);

//declare your aim by adding +10f to the local.z position of your turret. Not 50f, because if your
//car goes past 50f then it'll start shooting behind
aim = new Vector3(mousePos.x, mousePos.y, transform.localPosition.z+10f);
//rotate turret to mouse
//now make turret look at your aim not your mousePos - you want it to look at an X Y Z point, not X Y.
gunEnd.transform.LookAt (aim);
//get mouse click and asks if we can shoot yet
if (Input.GetKey(KeyCode.Mouse0)&&canShoot) {
StartCoroutine(shoot());
}
}

public IEnumerator shoot(){
//instantiates the bullet
gunEnd.transform.LookAt (aim);
bullet = Instantiate (bulletPrefab, gunEnd.transform.position, Quaternion.identity);
bullet.transform.LookAt (aim);
Rigidbody b = bullet.GetComponent<Rigidbody> ();
b.AddRelativeForce (Vector3.forward*force);
canShoot = false;

yield return new WaitForSeconds (fireRate);
canShoot = true;
}
}

无论位置或鼠标位置如何,这只会向后射击,在同一位置的玩家身后。

感谢您的阅读,希望对您有所帮助! :)

最佳答案

我认为问题出在这一行:

mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);

因为“屏幕位置”(Input.mousePosition)在转换为世界空间时没有任何“深度”,我怀疑 Camera.main.ScreenToWorldPoint 返回了错误的值,即使您尝试在几行之后设置 aim.z 的值。

试试这个:

    mousePos = Input.mousePosition;
mousePos += Camera.main.transform.forward * 10f ; // Make sure to add some "depth" to the screen point
aim = Camera.main.ScreenToWorldPoint (mousePos);

顺便说一句,在上面的代码中,使用了 Camera.main,但是您应该使用在 Start 函数中初始化的缓存版本:mainCam

关于c# - Unity3d,在鼠标位置射击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45159382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com