Query regarding bullet direction in 2d.
Hi there, I've been struggling with this for the past day or so. I'm attempting to have it so that whatever direction the player is facing, is the direction of travel of the instantiated bullet.. I thought maybe I'd cracked it by creating a variable for Player - to which there is an empty object that the gun is attached to and setting: transform.rotation = Player.transform.rotation; However I think I'm missing something - can someone point me in the right direction?
Thank you,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour {
public string buttonName = "Fire1";
public GameObject bulletPrefab;
public GameObject Player;
public Transform bulletOutput;
// Use this for initialization
void Start () {
transform.rotation = Player.transform.rotation;
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown (buttonName))
{
FireBullet();
}
}
void FireBullet () {
GameObject Clone;
Clone = (Instantiate(bulletPrefab, bulletOutput.position, transform.rotation));
Clone.GetComponent<Rigidbody2D> ().AddForce (transform.forward * 1000);
}
}
I've added in the below to the Player$$anonymous$$ovement script: Thinking I'd have to deal with the rotation there..
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player$$anonymous$$ovement : $$anonymous$$onoBehaviour {
public float speed = 6.0f;
private Vector3 previousLocation;
private Vector3 currentLocation;
public float rotationSpeed;
// Use this for initialization
void Start () {
rotationSpeed = 5;
}
// Update is called once per frame
void Update () {
previousLocation = currentLocation;
currentLocation = transform.position;
transform.position += Vector3.right * speed * Time.deltaTime * Input.GetAxis("Horizontal");
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
transform.position += Vector3.up * speed * Time.deltaTime * Input.GetAxis("Vertical");
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
}
}
Looks like your main issue is that you are adding a force in the direction of transform.forward. transform.forward references the local Z-axis, and in 2D you only have X and Y. Try using transform.right ins$$anonymous$$d.
Your answer
Follow this Question
Related Questions
How can i make a collision with the ground? 0 Answers
White line behind Object triggering collisions 0 Answers
How do I make a dash attack while doing a top down 2d game 0 Answers
Problem with colliders 0 Answers