- Home /
How can l tell my bullet to go right, not up. (C#)
Hello, l have a problem with my bullets from my tank. When l hover over my tank with the cursor and press down the left mouse button my bullet goes towards the top of the screen, which is good, but l want the bullet to go towards the right hand side of the screen. Thank you for any help. This is my code so far:
using UnityEngine;
using System.Collections;
public class PlayerBullet : MonoBehaviour
{
float speed;
void Start()
{
speed = 4f;
}
void Update()
{
Vector2 position = transform.position;
position = new Vector2 (position.x, position.y + speed * Time.deltaTime);
transform.position = position;
Vector2 max = Camera.main.ViewportToWorldPoint (new Vector2 (1, 1));
if(transform.position.y > max.y)
{
Destroy(gameObject);
}
}
}
Answer by Dave-Carlile · Aug 04, 2015 at 08:59 PM
Do you see the part of your code where it's changing position.y
each frame? And then destroying the game object once y
reaches a certain value? Well (and I'm assuming this is 2D) the y
vector component controls the vertical position, and the x
vector component controls the horizontal position.
So to move horizontally you need to change x
, just like you change y
to move vertically.
Answer by Cherno · Aug 04, 2015 at 09:03 PM
Change this line:
position = new Vector2 (position.x, position.y + speed * Time.deltaTime);
into this line:
position = new Vector2 (position.x + speed * Time.deltaTime, position.y);
Remember that x is left-right, and y is bottom-up.
Your answer
Follow this Question
Related Questions
seperation of prefabs with two dimensional terrain generation 0 Answers
Setting parent in instantiated class 3 Answers
Change position of camera on scene load? 1 Answer
Create a straight gradient equation with a grid of 3d objects 1 Answer
Following another object's position/rotation like parent/child relationship? 4 Answers