- Home /
Unity 2D - Bullets don't follow mouse
I'm trying to follow this video to make a 2d ranged combat system: https://www.youtube.com/watch?reload=9&v=bY4Hr2x05p8
I followed the video and compared my scripts to the project files from the video on github, and everything is the same, but when I try to play my verison, there are two problems: 1. The bullets only go up. 2. the gun sprite doesn't follow the mouse, it points -90 degrees from it's position.
this is the weapon script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
public float offset; //set to -90, like in the video
public GameObject projectile;
public Transform shotPoint; //an empty game object as child of the gun sprite, like in the video
private float timeBtwShots;
public float startTimeBtwShots;
void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (timeBtwShots <= 0)
{
if (Input.GetMouseButton(0))
{
Instantiate(projectile, shotPoint.position, Quaternion.identity);
timeBtwShots = startTimeBtwShots;
}
}
else
timeBtwShots -= Time.deltaTime;
}
}
this is the projectile script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour {
public float speed;
public float lifeTime;
public GameObject destroyEffect;
private void Start()
{
Invoke("DestroyProjectile", lifeTime);
}
private void Update()
{
transform.Translate(Vector2.up * speed * Time.deltaTime);
}
void DestroyProjectile() {
Instantiate(destroyEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
Up until this point I followed everything in the video, and I tried copying the final scripts from the github project, but the two problems I listed above still exist, please someone tell me what I'm doing wrong here.
Answer by triis4924 · Aug 05, 2019 at 01:57 PM
I had the same problem as I followed the tutorial, but I think I fixed it by writing: "transform.Translate(Vector2.right speed Time.deltaTime);" and not Vector2.up. If that doesn't work please message me again.
It didn't work, but I found a different tutorial that shows something similar that actually works: https://www.youtube.com/watch?v=01HVr1fp7pU
Your answer
Follow this Question
Related Questions
Shooting Towards mouse Cursor 1 Answer
How to make Enemy shoot at Player Top Down 1 Answer
How do I get my character to shoot a projectile in the direction of the cursor? 1 Answer
Camera script 1 Answer
2d bullet shot at bullet emitter 0 Answers