Unity Aiming Line 2D - unity3d

I am new at coding with Unity and wanted to create a game where the player should shoot a target. I want to draw a line from the players position to the mouse position and when the player hits space the line disappears and the bullet flies in that direction.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1")) {
Shoot();
}
}
void Shoot()
{
Instantiate(bulletPrefab,firePoint.position,firePoint.rotation);
}
}
I have this code for showing the bullet

I will but give you some hints about how I would do it (as the aswer should not involve providing your coded solution). The real appropiate question would be once you researched and tried out all of this, the concrete step with a reproducible example where you might have got stuck. Find more info about how to ask a good question here
The functions you need to achieve what you want are Input.mousePosition, the unity lineRenderer and maybe Debug.DrawRay to debug your directions in the screen.
For the concrete step of drawing the line you need to set the Input.mousePosition to the lineRenderer positions with SetPositions in an Update() so that when you shoot, you can make the line dissapear disabling the line renderer component, or resetting the positions or with other alternative depending on the behaviour you might need.
Good luck :)

Related

Why is rigidBody.velocity not very accurate in my unity2d project?

I was trying to make my object change direction when it moves by 1 unit, so i set its rigidbody.velocity to be 0.25, and set a coroutine that changes its direction every 4 seconds. But i noticed that it has some small inaccuracies (such as changing direction when moved by 0.998), which builds up to a lot after running for some time.
Now I know the best way is probably to just directly change transform.position in this case, but could someone tell me why does my previous method have these inaccuracies?
Edit:
To add a bit of context, im trying to replicate a traditional snake game but with smooth movement(in stead of jumping between the grids). It was a bit hard to explain how the direction can only be changed when the snake has reached a whole unit so i just said that the direction is changed every 4 seconds in the original post. Here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SnakeHead : MonoBehaviour
{
private Rigidbody2D rigidBody;
private Vector2 currDir;
[SerializeField] private float speed;
void Start()
{
rigidBody = gameObject.GetComponent<Rigidbody2D>();
currDir = Snake.Instance.GetDir();
StartCoroutine(Move());
}
IEnumerator Move()
{
while (GameManager.gameIsRunning)
{
currDir = Snake.Instance.GetDir();
rigidBody.velocity = currDir * speed;
yield return new WaitForSeconds(1 / speed);
}
}
}
note that i set speed to be 0.25 in the unity editor window.
im aware that changing transform.position directly is bad practice, but ive watched several tutorials and all of them did that on the snake's movement. Does anyone know if there's a better way?
It's pretty hard to make it such that you change direction exactly after 4 seconds. Using WaitForSeconds(4) will not wait exactly 4 second, instead it will wait at least 4 seconds as correctly mentioned in the comments. It largely depends on how frequently your coroutine is checked by the engine.
As you already mentioned, it would probably be a good idea to do some explicit actions. Either moving it "by hand" (not through the physics simulation), or periodically set the position to a known value.

(Unity) Is there a way to animate Line Renderer without code?

I'm prototyping a 2D space shooter, and i wanted a secondary special attack that creates a laser, completely kinematic, coming out of the ship's front. I've done the laser using Line Renderer and the Bloom Post Processing effect.
So I was wondering if it is possible to animate the line renderer on the animator.
I've tried to do it but it seems that the animator, as far as I can see on my Unity 2019.2.17f1 version, that it only appears to allow animations for the Line Renderer's material-related stuff, not related to the position array (curve), aside from the Width multiplier property, which I also need but isnt sufficient for the animation
Maybe I'm missing a name but it seems that you cant really modify the parameters if it's not via code.
Any ideas?
I'm not sure if or why it is not possible but most probably it is due to the fact that it is an array unlike all the properties you usually animate which are single values.
What you could do though if it is only supposed to animate e.g. the end point have a component like e.g.
public class LaserController : MonoBehaviour
{
public LineRenderer line;
public bool enableLaser;
public Vector3 endPoint;
private void LateUpdate ()
{
line.enabled = enableLaser;
line.SetPosition(1, endpoint);
}
}
And simply animate the fields of that one.
The answer is there isnt, and i switched to particle system for a more simple use.

Unity: Game Object cannot move to right for the first time I press right arrow of keyboard

Update: after go further with this book, I get the reason. It is the box colliders limitation of Unity it said in book. So I think we could close this ticket.
What said in the book:
"Right now, if you’re using box colliders on your tiles and on your player character, you might find that
you occasionally get stuck on things that you shouldn’t—your character may stop moving and press against
thin air. The problem normally occurs at the vertices between the closely positioned tiles, and unfortunately,
it seems that this is a slight issue with Unity itself rather than anything you can fix (apparently, it was
introduced in 4.3.1 and has yet to be resolved as of the time of writing).
If you do encounter this problem, just try using a polygon collider for Squarey himself, changing the
shape slightly by clicking Edit Collider, and then creating a small bump in the outline as in Figure 5-9 so that
you can “slide” over these imagined obstacles."
Following a book, I create a simple game using Unity 2D. It includes a GameObject named 'Player' which could do some simply action, move to left/right/jump when pressing leftArrow/rightArrow/Space key of my PC. And also some tiles as platform ground.
I found a problem that when the game is played, firstly the Player will drop on the platform then when I press Right Arrow Key, it has no effect. But if I press Left Key or Space, the Player will go left or jump then the Right Click will take effect...
This problem takes me for hours!
Searching the internet but no answer found. One clue I found is that when I uncheck the Freeze Rotation option under RigidBody2D, then right move worked but I don't know why yet.
Here is my code, guys your help will be appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Rigidbody2D rb;
public int moveSpeed;
public int jumppower;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool onGround;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius,
whatIsGround);
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
}
if (Input.GetKey(KeyCode.RightArrow))
{
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
}
if (Input.GetKey(KeyCode.Space) && onGround)
{
rb.velocity = new Vector2(rb.velocity.x, jumppower);
}
}
}
OKay, let me close this question. The reason why the Player is occasionally stop during the moving is because the limitation of Box Collider.
The workaround could be using polygon collider instead and change the shapes, that is what is said on the book.
Of course I have a try on my project, it works actually. Thanks guys, the case is closed now and I will learn Unity step by step since the interest of games!

I am trying to check collision in unity for my bullet and enemy, but it doesnt work

I have this script attached to my bullet, which is currently just cube in 2d space. it has rigidbody2d, boxcollider and istrigger is checked.
using UnityEngine;
using System.Collections;
public class EnemyBulletCollision : MonoBehaviour {
void OnTriggerEnter(Collision coll)
{
if(coll.gameObject.tag == "Enemy") {
Destroy(coll.gameObject);
Destroy(gameObject);
}
}
}
Enemy is also cube with BoxCollider, Rigidbody2d and istrigger checked.
Nothing just happens. i tried all kind of things, but none works. Kind of stuck here.
When you use Unity's 2D physics, you must use the corresponding 2D methods (all the same methods, just ending with "2D"). So instead of using OnTriggerEnter, you need to use OnTriggerEnter2D.

Unity - Inconsistant speed of object following raycast2D

So im creating a simple game and one component of the game is a greendot following the outside of the level. I got this working using a raycast in the middle which rotates and gives the position of collision the the gameobject.
game overview
The problem is that the speed is inconsistant at the moment since the distance between two collisions can be further distance if i have a slope. I also have the feeling that there should be a easier way to get the same result. What are your thoughts?
public class FollowPath : MonoBehaviour {
Vector3 collisionPos;
public GameObject greenDot;
void Update ()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);
transform.Rotate(0.0f, 0.0f, 3);
if (hit.collider != null)
{
collisionPos = hit.point;
}
greenDot.transform.position = collisionPos;
}
}
I'm not sure if you will like this answer, as it suggests a complete departure from the way you were trying to do it.
A simple way to do this, would be to give your moving dot GameObject a Rigidbody2D component, AND a CircleCollider component.
Then, make your walls, and add to each an EdgeCollider component.
You'll probably also want to add a PhysicsMaterial2d to each GameObject with a Collider and set the friction and bounciness values for each.
Once this is setup, you can apply an initial force to the rigid body ball to get it moving, and it will bounce off the walls just like a ball does, using the Unity physics engine. No code would be needed in you update functions.