- Home /
Question by
marvalshot · Apr 18, 2014 at 09:16 PM ·
cameramouserigidbody2dscrollingaim
Proper mouse aim of bullets with rigidbody2d and side scrolling?
The code below works fine as long as the shooter and background is still. It shoots bullets to the spot the player clicks on the screen. However when scrolling the player shoots toward to the original click spot which is of course now different because the camera has moved. Is there a formula for determining the spot or perhaps a better alternative. I just want to be able to aim and fire to the aim spot while moving the player object around the world. Thanks for any input
Vector3 mousePos = Input.mousePosition;
Vector3 wantedPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 1f));
shotAngle = wantedPos - transform.position;
Rigidbody2D instance = Instantiate(prefabBullet, this.transform.position, this.transform.rotation) as Rigidbody2D;
instance.rigidbody2D.AddForce(shotAngle * shotPower);
Comment
The other thing to consider is that the player has velocity too. In order for the bullets to travel at the same speed within the player's moving frame of reference, you need to add the player's velocity to the bullet too.