I’m very new to Unity and C#. I’m trying to create my first game and I have now invested about 15+ hours trying to find solutions to this issue...I’m stumped!
My player sprite (blue square) needs to launch a prefab sprite (red circle) of similar size ‘appearing’ to originate from itself. Here is a GIF of what I have so far...I don’t want the blue cube to collide and go flying.
After clicking and dragging on Player (drag-to-aim) via OnMouseDrag to set the target vector, I’m trying to Instantiate a prefab sprite (Dynamic RigidBody2D, CircleCollider2D) using the Player sprite’s position (a Dynamic RigidBody2D, BoxCollider2D) and have it APPEAR to be originating from inside the Player object. Launch is triggered via function called in OnMouseUp. Both objects should immediately come under control of Physics to collide with the environment which will include other moving RigidBody2D objects later. Targeting should allow 360 degrees to include straight into an obstacle allowing rebound effect.
Here is some excerpts of my code:
using System.Collections;
using UnityEngine;
public class Teleportation_Grenade : MonoBehaviour {
/*
This script is attached to Player and requires_
projectile prefab.
tested with thrust set between 100 and 200.
*/
public float thrust;
public Transform prefab;
public LineRenderer playerShotLine;
private Vector2 playerToMouse;
private Vector2 targetVector;
//...
void OnMouseDrag()
{
Vector3 mouseWorldPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Vector2 playerToMouse = mouseWorldPoint - transform.position;
mouseWorldPoint.z = 0f;
playerShotLine.SetPosition (0, transform.position);
playerShotLine.SetPosition (1, mouseWorldPoint);
playerShotLine.sortingOrder = 3;
//opposite direction of line renderer
targetVector = -playerToMouse;
}
void OnMouseUp()
{
SpawnPrefab ();
}
void SpawnPrefab()
{
Instantiate(prefab, new Vector3(transform.position.x, transform.position.y, 0), Quaternion.identity);
prefab.GetComponent<Rigidbody2D> ().AddForce (targetVector * thrust, ForceMode2D.Impulse);
}
}
This is only one of many, many iterations. It's the gist of it though. I appreciate any insight from the community.
Instantiate
Red Circle from Blue Square and Blue Square should not move, if is that so, why didn't you assign different layer to Blue Square and uncheck the collision from Collision Matrix? Edit -> Project Settings -> Physics2D \$\endgroup\$