【发布时间】:2017-12-16 11:38:12
【问题描述】:
我使用统一资产第一人称控制器制作了一个游戏,以允许玩家移动并让他们环顾四周。我在射线投射穿过并实例化子弹的位置放置了一个十字准线。超过一定角度的子弹射击没有问题。子弹顺着十字准线射向中心,但如果我往下看太远,它们就不再射向十字准线所在的位置,而是直接从相机中射出。
我认为第一人称控制器制作的胶囊可能是问题所在,因为我在代码中找不到任何内容。
视频链接:https://youtu.be/zf2EuL7e_i4
Bullet Listener.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletListener : MonoBehaviour {
public Camera mainCamera;
public BulletContoller bulletPrefab;
public GameObject cursor;
private Vector3 cursorPosition;
void Update () {
if (Input.GetMouseButtonDown (0)) {
cursorPosition = cursor.transform.position;
//create ray from camera to mousePosition
Ray ray = mainCamera.ScreenPointToRay (cursorPosition);
//Create bullet from the prefab
BulletContoller newBullet = Instantiate (bulletPrefab.gameObject).GetComponent<BulletContoller> ();
//Make the new bullet start at camera
newBullet.transform.position = mainCamera.transform.position;
//set bullet direction
newBullet.SetDirection (ray.direction);
//Create Bullet Sound
AudioSource audio = GetComponent<AudioSource>();
audio.Play ();
}
}
}
Bullet Controller.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletContoller : MonoBehaviour {
Rigidbody rb;
public float bulletForce;
bool firstTime = false;
Vector3 direction;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody> ();
}
public void SetDirection (Vector3 dir) {
direction = dir;
firstTime = true;
}
void OnCollisionEnter (Collision col) {
//code for when bullet hits something
if (col.gameObject.name == "Target") {
this.gameObject.name = "Hit";
}
}
void FixedUpdate () {
if (firstTime) {
rb.AddForce (direction * bulletForce);
firstTime = false;
}
}
}
【问题讨论】:
-
我怀疑你的光标位置有问题。你确认它是正确的吗?
-
我该怎么做?
标签: c# unity3d unity5 game-physics raycasting