I am having an issue on the laser defender course, i have gone out of my way to integrate mobile into the game as I do intend to share this with my friends once im done, so some of my coding differs from the instructors since I have also gone through other sources to get lessons on how to integrate mobile controls. The issue is not from them however, it seems to be from the line attempting to access the rigidbody of the projectile laser from the player. This is my code so far…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityStandardAssets.CrossPlatformInput;
public class Player : MonoBehaviour
{
//remember to improve the laser upgrade system
//Variables
[SerializeField] float moveSpeed = 10f;
[SerializeField] float padding = 0.8f;
//adding upgrade system later
[SerializeField] GameObject laserPrefabOne;
[SerializeField] GameObject laserPrefabTwo;
[SerializeField] GameObject laserPrefabThree;
[SerializeField] float projectileSpeed = 10f;
float xMin;
float xMax;
float yMin;
float yMax;
void Start()
{
SetUpMoveBoundaries();
}
// Update is called once per frame
void Update()
{
Move();
Fire();
}
//made public so it could be assigned to a button on UI for android
public void TakeShot()
{
GameObject laser = Instantiate(laserPrefabOne, transform.position, Quaternion.identity);
laser.GetComponent<RigidBody2D>().velocity = new Vector2(0, projectileSpeed);
}
private void Fire()
{
if(Input.GetButtonDown("Fire1"))
{
TakeShot();
}
}
private void Move()
{
//move the player and using cross platform to intigrate with UI joystick for android
var deltaX = CrossPlatformInputManager.GetAxisRaw("Horizontal") * Time.deltaTime * moveSpeed;
var deltaY = CrossPlatformInputManager.GetAxisRaw("Vertical") * Time.deltaTime * moveSpeed;
//Clamp to screen
var newXPos = Mathf.Clamp(transform.position.x + deltaX, xMin, xMax);
var newYPos = Mathf.Clamp(transform.position.y + deltaY, yMin, yMax);
transform.position = new Vector2(newXPos, newYPos);
}
private void SetUpMoveBoundaries()
{
Camera gameCamera = Camera.main;
xMin = gameCamera.ViewportToWorldPoint(new Vector3(0,0,0)).x+padding;
xMax = gameCamera.ViewportToWorldPoint(new Vector3(1,0,0)).x-padding;
yMin = gameCamera.ViewportToWorldPoint(new Vector3(0,0,0)).y+padding;
yMax = gameCamera.ViewportToWorldPoint(new Vector3(0,1,0)).y-padding;
}
}