Problems with my 2d Topdown game.
So I made so that the player looks at my mouse, but I gave him a little delay by rounding up the rotation value or sth. (What I wanted to say is that I have no idea about how I did it) Then I made a laser for aiming using raycast and a line renderer. Everything works fine .... buuuuuut, if I set my smoothing to something other than 0 ... means no smoothing, the laser starts lagging and jumping forth and back if I move (And ONLY if I move). Line Renderer is not the problem, raycast isnt aswell. So I think that my smoothing is crap ... If anyone wants to help, heres the code. Laser object is a child of the player btw.
Player
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
//Variables
public float movSpeed = 90;
Rigidbody2D rb2d;
private float zVelocity = 0.0F;
public float smooth;
//Code
void Start() {
//Define stuff
rb2d = gameObject.GetComponent<Rigidbody2D>();
}
void FixedUpdate(){
//Movement
Vector2 input = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
rb2d.AddForce(input * movSpeed);
if (Mathf.Abs(rb2d.velocity.x) > movSpeed){
rb2d.velocity = new Vector2(Mathf.Sign(rb2d.velocity.x)* movSpeed, rb2d.velocity.y);
}
if (Mathf.Abs(rb2d.velocity.x) > movSpeed){
rb2d.velocity = new Vector2(rb2d.velocity.x, Mathf.Sign(rb2d.velocity.y) * movSpeed);
}
}
void Update() {
//Follow mouse
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
float z = Mathf.SmoothDampAngle(transform.eulerAngles.z,rot_z - 90, ref zVelocity, smooth);
transform.rotation = Quaternion.Euler(0f, 0f, z);
}
}
Laser
using UnityEngine;
using System.Collections;
public class Laser : MonoBehaviour {
LineRenderer lineRenderer;
public Vector2 laserHit;
public LayerMask layerMask;
Vector3 pointInfront;
Vector4 laserGray;
public Material laserMat;
void Start () {
lineRenderer = gameObject.AddComponent<LineRenderer>();
laserGray = new Vector4(0,0,0,0.2f);
}
void Update(){
pointInfront = transform.up * 30 ;
}
void LateUpdate () {
//Raycasting
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up, 30, layerMask);
Debug.DrawRay(transform.position, transform.up*100);
if (hit.collider != null){
laserHit = hit.point;
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, laserHit);
lineRenderer.SetWidth(0.08f,0.05f);
lineRenderer.material = laserMat;
}
else {
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, transform.position + pointInfront);
lineRenderer.SetWidth(0.08f,0.05f);
lineRenderer.SetColors(laserGray,laserGray);
lineRenderer.material = laserMat;
}
}
}
Comment