I’m making a 2d horizontal shmup and the camera and ship are scrolling from left to the right. When I make the enemies aiming to the playership the bullets won’t hit the playership because of the scrolling. How can I calculate the target position for aiming in dependece of the scrolling in 2D (x and y) of the camera?
Usually the player and bullets move in world space, completely independent from the camera. The camera only frames the game world, it shouldn’t affect the gameplay.
Is that not the case for your game?
Or maybe it’s the player moving and not actually the scrolling that’s making the bullets miss? In that case you can search for “aiming”, “moving” and “prediction” to find tons of threads here or various articles and tutorials across the internet.
You make the enemy shoot at the player’s position plus the player’s velocity.
Here’s an example:
using UnityEngine;
public class TargetPrediction : MonoBehaviour
{
public Rigidbody bullet;
public Rigidbody target;
float bulletSpeed;
Vector3 prediction;
void Start()
{
bulletSpeed=10;
InvokeRepeating("Shoot",2,3);
}
void Update()
{
float targetDistance=Vector3.Distance(transform.position,prediction);
prediction=target.position+target.velocity*targetDistance/bulletSpeed;
transform.LookAt(prediction);
}
void Shoot()
{
Rigidbody b=Instantiate(bullet,transform.position,Quaternion.identity);
b.AddForce(transform.forward*bulletSpeed,ForceMode.Impulse);
}
}
I mean if the player ship isn’t moving only the scrolling so that the bullet should hit the target.
It seems it really depends on your setup, you need to post some explanation of how you move your player, bullets and camera.
As I said, usually the player and bullets move in world space, so that the camera movement doesn’t have any effect on them. It sounds like you’re using a different setup.
Are you maybe keeping the camera at the same position and scroll the level/background instead?
I saw your video in the other thread. The ship is clearly moving to the right with the camera and that’s why the enemy’s projectiles are missing and going to the left. The enemy should take the ship’s velocity into account when aiming at the ship.
Thank you very much, it works.