我正在尝试按照大多数 fps 游戏的方式放置我的枪, 例如这样:
但是当我尝试定位并随播放器旋转它时遇到问题。枪不能很好地旋转,并且位置不总是相同。
有没有办法让枪保持在同一位置并使其随着玩家旋转良好?
但我的主要问题是枪的位置,我需要它像在每个 fps 中那样保持在一个地方,当我开始游戏并选择一把枪时,它会因为旋转而在屏幕上的不同位置生成。
这是我尝试使用的代码:
GameObject temp = GameObject.Find(gameObject.name);
playerGuns[keyPress] = Instantiate(temp, Player.transform.position
+ new Vector3(-2f, 3f, 4f), Quaternion.identity) as GameObject;
playerGuns[keyPress].name = gameObject.name;
playerGuns[keyPress].tag = gameObject.tag;
playerGuns[keyPress].transform.parent = Player.transform;
playerGuns[keyPress].transform.rotation.SetLookRotation(Player.transform.position);
最佳答案
好吧,这是我 promise 的答案:
第一个问题是如何设置旋转,SetLookRotation
接受 2 个参数,Vector3 view
和 Vector3 up
第二个是默认为 Vector3.up
。你正在传递player.transform.position,用于“ View ”,这是你想要变换查看的方向。这样想,如果我在远东面向西,我的武器将面向东......(这是假设 SetLookRotation 将其标准化。)这是因为我的实际位置是东边,来自某个任意的原点。您可以使用的东西是 player.transform.forward
。
要生成一个对象并使其具有相同的相对旋转和位置,您可以像在原始代码中一样使用Instantiate
。 instantiate 有多个版本.
在评论中我说给自己一个offsetPosition和一个eulerAngle,但是如果你有多种武器,这可能会很麻烦。我提到过我会就如何为多种武器进行设置提供建议......所以就开始吧。
可编写脚本的对象,
在 Unity 中,您可以创建此对象来存储有关特定对象的信息,例如“武器”对象可以如下所示:
using UnityEngine;
using System.Collections;
[CreateAssetMenu(fileName = "New Weapon", menuName = "Weapon")]
public class WeaponObject : ScriptableObject {
public string objectName = "New Weapon";
public Vector3 offSetPosition;
public Vector3 startOffsetRotation;
public float fireRate;
// Using a gameObject to store the weapon model so you can technical
// store the firing point.
public GameObject weaponModel;
}
您现在可以通过右键单击 Assets 目录并转到“创建”->“武器”来创建新对象。完成此操作后,您可以重命名它创建的对象,检查器将显示您可以修改的该对象的所有公共(public)字段。
有了这个,你可以创建多种武器,并将它们的数据存储在武器管理器中,从而生成每种武器。像这样的东西:
WeaponObject weapon = WeaponManager.getWeapon(keyPress);
playerGuns[keyPress] = Instantiate(weapon.weaponModel, Player.transform.position + weapon.offsetPosition, Quaternion.identity) as GameObject;
playerGuns[keyPress].name = weapon.objectName;
playerGuns[keyPress].transform.parent = Player.transform;
playerGuns[keyPress].transform.eulerAngles = weapon.startOffsetRotation;
if(player.weaponScript != null) {
// we can have a single script for all of our weapons, and the WeaponObject
// will control its firerate, which projectiles it fires, etc.
player.weaponScript.setWeapon(weapon);
}
关于c# - 将枪放置在固定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50122746/