Laser Collider As Long As Beam - c#

{
private LineRenderer lineRenderer;
public Transform LaserHit; //this all works
void Start()
{
lineRenderer = GetComponent<LineRenderer>();
lineRenderer.useWorldSpace = true; //this works too
}
void Update()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);
LaserHit.position = hit.point;
lineRenderer.SetPosition(0, transform.position); //the laser is shown like i want
lineRenderer.SetPosition(1, LaserHit.position);
}
}
I have this laser script and it works! A laser IS shown, I want my player to die to the laser i have the death animation and respawning ALREADY MADE. For The Player To Die He has TO touch a BoxCollider2D preferebly one set to trigger. I want to put the BoxCollider2D (preferebly set to trigger) for as long as the laser beam is, so that you dont die where thre isnt a laser beam shown.
I hope i made myself clear and Please anwser :D thanks

You could do something like
public Collider collider;
and then
var delta = LaserHit.position - transform.position;
collider.transform.position = (LaserHit.position + transform.position) * 0.5f;
collider.transform.right = delta;
collider.transform.localScalee = new Vector3(delta.magnitude, 0.1f, 1f);

Related

Multiple touch unity mobile

I am creating a 2d mobile game where one of the scripts uses a joystick to move and the other script lets the player shoot an object when tapping anywhere on the screen. The issue is when using the joystick it also shoots at the same time in that direction. Is there a way to separate the touches so when you use the joystick it does not immediately shoot to that direction but the player can still move and shoot anywhere at the same time?
Move Code
private void Update()
{
Vector2 moveInput = new Vector2(joystick.Horizontal, joystick.Vertical);
moveAmount = moveInput.normalized * speed;
}
Shoot code
private void Update()
{
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
transform.rotation = rotation;
if(Input.GetMouseButton(0))
{
if (Time.time >= shotTime)
{
Instantiate(projectile, shotPoint.position, transform.rotation);
shotTime = Time.time + timeBetweenShots;
}
}
}
Instead of using Input.mousePosition you'll have to use Input.GetTouch. You can loop through it using Input.touchCount to find the first touch that is not interacting with a ui element, than use that touch instead of Input.mousePosition to find the direction to shoot (or not shoot if there is no touch). To find out if a specific touch is over ui you need a reference to the scene's EventSystem (or use EventSystem.current), and use EventSystem.IsPointerOverGameObject with Touch.fingerId.
If the joystick is not a ui element you'll need a different way to detect if the touch is over the joystick. For example you could check the pixel position, or see if the joystick itself has an "interacting fingerId". But with the assumption that the joystick is an ui element, here's one way to do what I wrote above: (untested)
private void Update()
{
var eventSystem = EventSystem.current;
for (var i = 0; i<Input.touchCount; i++)
{
var touch = Input.GetTouch(i);
if (eventSystem.IsPointerOverGameObject(touch.fingerId))
{
continue;
}
ShootToScreenPos(Vector2 screenPos);
break;
}
}
private void ShootToScreenPos(Vector2 screenPos)
{
Vector2 direction = Camera.main.ScreenToWorldPoint(screenPos) - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
transform.rotation = rotation;
if (Time.time >= shotTime)
{
Instantiate(projectile, shotPoint.position, transform.rotation);
shotTime = Time.time + timeBetweenShots;
}
}

How to make a smooth crosshair in Unity3D?

In Unity 3D I'd like to create a crosshair for my top-down 2D-shooter that gradually moves to its target whenever the player has the same x-position as the target.
The problem is that I want a smooth animation when the crosshair moves to the target. I have included a small gif from another game that shows a crosshair I'd like to achieve. Have a look at it:
Crosshair video
I tried to do that with the following script but failed - the crosshair jumps forth and back when the enemies appear. It doesn't look so smooth like in the video I mentioned above.
The following script is attached to the player:
[SerializeField]
private GameObject crosshairGO;
[SerializeField]
private float speedCrosshair = 100.0f;
private Rigidbody2D crosshairRB;
private bool crosshairBegin = true;
void Start () {
crosshairRB = crosshairGO.GetComponent<Rigidbody2D>();
crosshairBegin = true;
}
void FixedUpdate() {
//Cast a ray straight up from the player
float _size = 12f;
Vector2 _direction = this.transform.up;
RaycastHit2D _hit = Physics2D.Raycast(this.transform.position, _direction, _size);
if (_hit.collider != null && _hit.collider.tag == "EnemyShipTag") {
// We touched something!
Debug.Log("we touched the enemy");
Vector2 _direction2 = (_hit.collider.gameObject.transform.position - crosshairGO.transform.position).normalized;
crosshairRB.velocity = new Vector2(this.transform.position.x, _direction2.y * speedCrosshair);
crosshairBegin = false;
} else {
// Nothing hit
Debug.Log("nothing hit");
crosshairRB.velocity = Vector2.zero;
Vector2 _pos2 = new Vector2(this.transform.position.x, 4.5f);
if (crosshairBegin) crosshairGO.transform.position = _pos2;
}
}
I think you need create a new variable call Speed translation
with
speed = distance from cross hair to enemy position / time (here is Time.fixedDeltaTime);
then multiply speed with velocity, the cross hair will move to enmey positsion in one frame.
but you can adjust speed by mitiply it with some float > 0 and < 1;

How to make the tank look to the side of the mouse and shoot where the player clicks?

I have a tank in a 3rd person 3D game so my camera is looking at the tank from above and a bit from the side. I need the turret of my tank to rotate on the y-axis so that it always looks at the mouse and shoot where the player clicks. The problem is that my game is 3D and all I get is that it actually looks at the mouse (like upwards to the sky).
This is the code I have now:
private Vector3 target;
private Camera cam;
private void Start()
{
cam = Camera.main;
}
void Update()
{
Vector2 mousePos = new Vector2();
mousePos.x = Input.mousePosition.x;
mousePos.y = Input.mousePosition.y;
target = cam.WorldToScreenPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
transform.LookAt(target);
}
Your problem lies here: target = cam.WorldToScreenPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
What you actually need to do is generate a ray that comes out of the camera with ScreenPointToRay(), then do a Physics.Raycast() with that ray and get the RaycastHit from it. Then set the target equal to the RaycastHit.
For example:
Ray screenRay;
RaycastHit screenRayHit;
float maxRaycastDistance;
screenRay = cam.ScreenPointToRay(mousePos.x, mousePos.y);
if(Physics.Raycast(screenRay, out screenRayHit, maxRaycastDistance))
{
target = screenRayHit;
}
else
{
//just sets the turret to aim at the endpoint of the ray if you aim at nothing
target = screenRay.GetPoint(maxRaycastDistance);
}

How to face character in its movement direction and at the same time keep it aligned to any surface?

I want to move my player character(human) on a curved surface. But at the same time character shall stay perpendicular to the surface normals and it should face in the movement direction and can handle collisions(if there is a wall ahead, shall not be able to go through it).
I tried to make a parent stay over normals and change the child local rotation towards direction of motion of its parent. But it has several limitations as of now.
Here is the code what i was using:
[SerializeField] float raycastLength = 1f;
bool canPlayerMove = true;
public float speed = 2f;
public Vector3 offset; //object's position offset to ground / surface
public Quaternion childDirection;
private void Update()
{
float moveHorizontal = SimpleInput.GetAxis("Horizontal");
float moveVertical = SimpleInput.GetAxis("Vertical");
Ray ray = new Ray(transform.position, -transform.up);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, raycastLength))
{
transform.rotation = Quaternion.LookRotation(Vector3.up, hitInfo.normal);
transform.position = hitInfo.point + offset;
Debug.DrawLine(ray.origin, hitInfo.point, Color.red);
}
if (canPlayerMove)
{
Vector3 movement = new Vector3(moveHorizontal, 0, moveVertical);
if (movement != Vector3.zero)
{
childDirection = Quaternion.Slerp(transform.GetChild(0).localRotation, Quaternion.LookRotation(movement), 0.15F);
transform.GetChild(0).localRotation = childDirection;
}
transform.Translate(movement * speed * Time.deltaTime, Space.Self);
}
}
first to not make your player go thru walls you want to add a collider to your walls and not set it as trigger, you will also need a rigidbody on your player and this will help in the next steps.
Secondly you will need to acces the rigidBody in code using this: (if you Check Use Gravity it will also stay on your terrain that you made)
private Rigidbody rb;
private float speed = 7.5f;
private void Start()
{
//this gets the rigidbody on the gameObject the script is currently on.
rb = this.GetComponent<Rigidbody>();
}
private void Update()
{
float hor = Input.GetAxis("Horizontal");
float vert = Input.GetAxis("Vertical");
//this will move your player frame independent.
rb.MovePosition(this.transform.position + new Vector3(hor, 0, vert) * speed *
Time.deltaTime);
}
Also make sure that you have a rigidBody on your player, else it will throw an error.

Unity Shoot Ball From POV of Camera

I know this has been asked a few times but I believe my question can be solved without too much trouble (hopefully!) and is somewhat unique. I'm writing a mini-golf script that shoots the ball, intended to shoot away from the POV of the camera. I can't get it to do so however. I'm sure it has something to do with camera.transform but not sure. I'm a total noob to coding in Unity. I just need a simple, straightforward way to get this dang golf ball to travel in a straight line in whatever direction the camera is facing. Please help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HitBall2 : MonoBehaviour
{
Rigidbody rigidBody;
bool StartedShot;
Vector3 shotStart;
Vector3 shotEnd;
Vector3 direction;
public float distance;
public float forceAdjust = 0.05f;
void Start()
{
rigidBody = this.GetComponent<Rigidbody>();
StartedShot = false;
}
void Update()
{
if (Input.GetMouseButtonUp(1))
{
rigidBody.velocity = Vector3.zero;
this.transform.position = Vector3.zero;
StartedShot = false;
}
// Starting shot
if (!StartedShot && Input.GetMouseButtonDown(0))
{
StartedShot = true;
shotStart = Input.mousePosition;
}
// Ending shot
if (StartedShot && Input.GetMouseButtonUp(0))
{
shotEnd = Input.mousePosition;
direction = Camera.main.transform.forward - shotEnd;
float distance = direction.magnitude;
StartedShot = false;
Vector3 shootDirection = new Vector3(direction.x, 0.0f, direction.y);
rigidBody.AddForce(shootDirection * rigidBody.mass * forceAdjust, ForceMode.Impulse);
}
}
}
As mentined in comments above, to shoot forward just use cameras transform.forward
Okay I changed the script as follows and the ball now travels away from the camera. There's a little problem with the velocity of the ball and the little y-axis jump it does but I'm sure it's easily figured out.
changed " Vector3 shootDirection = new Vector3(direction.x, 0.0f, direction.y);"
to Vector3 shootDirection = Camera.main.transform.forward;
Thanks everyone!

Categories