- Home /
The bullet doesn't move correctly
Hi, i want to touch the screen and instanciate a bullet in that position
I have this code for instantiate the bullet:
> public GameObject bullet;
public Camera myCam;
private Touch touch;
public int numeroZ = 4;
void Update()
{
for (var i = 0; i < Input.touchCount; i++)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
Vector3 touchPos = Input.GetTouch(i).position;
print(touchPos);
touchPos.z = numeroZ;
var createPos = myCam.ScreenToWorldPoint(touchPos);
Instantiate(bullet, createPos + new Vector3(0, 0, -10), Quaternion.identity);
}
}
}
And this code for the movement of the bullet:
public Vector3 mov;
public int lifeTime;
private void Start()
{
Invoke("DestroyBullet", lifeTime);
}
void Update()
{
transform.Translate(mov * Time.deltaTime);
}
void DestroyBullet()
{
Destroy(gameObject);
}
And this is the result, even if I touch the edges of the screen and the bullet instantiate in the the touch position when it moves doesn't go in the touch position direction
So the bullet does instantiate in the proper location? The movement of the bullet just doesn't follow the proper direction?
Answer by Adamcbrz · Mar 28, 2020 at 02:13 AM
Your dealing with a perspective camera so you have to take into account the fov angle when determine move direction. Here is a image that will hopefully help:
The cyan line is what you are getting because you are just using a forward vector to move your bullet.
The red line is what you are expecting. What you need to do is use your touch point and use Camera.ScreenPointToRay to fine direction you need to travel and set your move vector to that direction.