从主摄像机射击射弹时左右瞄准

时间:2018-04-16 23:56:59

标签: c# unity3d unityscript

我有一个脚本设置,以便我可以从相机的角度拍摄无限制的预制件,但是球直接射死...我不确定我的脚本是否需要调整或是否有检查员设置需要调整的主摄像头。基本上如果我的光标位于左侧,我希望球朝那个方向而不是在屏幕中间拍摄。

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

public class Person : MonoBehaviour {

public GameObject projectilePrefab;
public Text countText;

private int count;
void OnGUI(){
    GUI.Box(new Rect(Screen.width/2,Screen.height/2, 10, 10), "");
}

// Use this for initialization
void Start () {
    count = 0;
    setCountText();

}

private void setCountText()
{
    countText.text = "Ammo Fired: " + count;
}

// Update is called once per frame
void Update () {

}

void LateUpdate()
{
    float x = Input.GetAxis("Mouse X") * 2;
    float y = Input.GetAxis("Mouse Y");

    float yClamped = transform.eulerAngles.x + y;

    transform.rotation = Quaternion.Euler(yClamped,
        transform.eulerAngles.y, transform.eulerAngles.z);

    transform.RotateAround(new Vector3(0, 3, 0), Vector3.up, x);
}

void FixedUpdate()
{
    if (Input.GetButtonDown("Fire2")) //Right click. use Fire1 for left click
    {
        GameObject projectile = Instantiate(projectilePrefab, 
            transform.position, transform.rotation) as GameObject;
        Rigidbody rb = projectile.GetComponent<Rigidbody>();
        rb.AddRelativeForce(Vector3.forward * 500000);

        count++;
        setCountText();
    }
}

}

2 个答案:

答案 0 :(得分:2)

扎克。您需要使用新预制件的前沿位置。

projectile.GetComponent<Transform>().forward

与使用编辑/世界前沿位置相反。

答案 1 :(得分:1)

使用:

rb.AddRelativeForce(projectile.transform.forward * 500000);

确实,projectile.transform.forward会给你刚刚产生的射弹的前进方向,而Vector3.forward会给你世界的前进方向(它基本上只是Vector3的快捷方式(0,0, 1))