Unity3dFPSガンの反動



Unity3d Fps Gun Recoil



銃が発射された後、一定の距離だけ上にオフセットし、次にゆっくりと下に移動してリセットします(csを模倣)

画像



反動を減らす

画像



using UnityEngine using System.Collections public class Camera2Follower : MonoBehaviour { // Gun cd timer float timer // recoil force the angle of the previous gun camera Vector3 s_pre_euler public float gun_end_force = 0.53f // The size of the gun recoil (you can increase it first to facilitate debugging) void Update () { .... timer += Time.deltaTime if (Input.GetButton('Fire1') && timer >= 0.15) { // reset the timer timer = 0f s_pre_euler = transform.eulerAngles // recoil rotationY += Input.GetAxis('Mouse Y') * sensitivityY + gun_end_force Quaternion yQuaternion2 = Quaternion.AngleAxis(rotationY, Vector3.left) transform.localRotation = originalRotation * yQuaternion2 } // Check if the mouse has moved if (Input.GetAxis('Mouse Y') != 0) { //Debug.Log('X: ' + transform.eulerAngles) s_pre_euler = transform.eulerAngles rotationY += Input.GetAxis('Mouse Y') * sensitivityY rotationY = ClampAngle(rotationY, minimumY, maximumY) Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, Vector3.left) transform.localRotation = originalRotation * yQuaternion } else { recoverGun() } } // Restore the previous position of recoil void recoverGun() { s_pre_euler.y = transform.eulerAngles.y Quaternion current_cam = Quaternion.Euler(transform.eulerAngles) Quaternion target_cam = Quaternion.Euler(s_pre_euler) transform.eulerAngles = Quaternion.Slerp(current_cam, target_cam, 5 * Time.deltaTime).eulerAngles } void Start () { s_pre_euler = transform.eulerAngles } // limit angle public static float ClampAngle (float angle, float min, float max) { if (angle <-360F) angle += 360F if (angle > 360F) angle -= 360F return Mathf.Clamp (angle, min, max) } }

csガンの反動を見て、まだ左右の揺れがあることがわかったので、コードを追加しました

y_angle_mat = xxxxxxxx // Up and down direction .... // Add in the gun firing method area float xAngle = Random.Range(0.0f,1.0f) Quaternion x_angle_mat = Quaternion.AngleAxis(xAngle, Vector3.up) transform.localRotation = originalRotation * y_angle_mat * x_angle_mat // Equivalent to multiplying a matrix