@hanatan079 (はなたん .)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

【unity】クローン で生成した位置のズレについて

現在、シューティングゲームの実装をしております。
Spaceキーを押すと、銃弾のクローンが生成されプレファブのtransform.positionの値から、銃弾が出るようにしたいです。

銃アセット(Player)と銃弾アセット(Bullet)は別になっており、transform.positionも異なります。

変更したいコード
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
        }

PlayerController.csで上記のコードを、記載すると銃アセット(Player)のtransform.positionになってしまい、発射される銃弾の位置がずれてしまいます。
銃弾アセットのtransform.positionを取得する場合には、どのようなコードに変更すればよろしいでしょうか。

1発目の位置にしたいが、2発目以降のクローンは、Playerのyの位置から発射されてしまう。

Player position (0,1,-35)
Bullet position (0,6,-41)

スクリーンショット 2022-11-07 22.58.15.png


PlayerContlloer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float horizontalInput;
    public float speed = 10.0f;
    public float xRange =25;
    public GameObject projectilePrefab;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);

        if(transform.position.x < -xRange)
        {
            transform.position = new Vector3(-xRange,  transform.position.y, transform.position.z);
        }
        if (transform.position.x > xRange)
        {
            transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
        }

    }
}

解答をお待ちしております。
よろしくお願い致します。

0 likes

1Answer

以下のように書くことで、Instantiateで生成した弾体オブジェクトbulletの位置を、変数bulletPositionに得ることができます。

var bullet = Instantiate (projectilePrefab, transform.position, projectilePrefab.transform.rotation);
var bulletPosition = bullet.transform.position
1Like

Your answer might help someone💌