Unity attach Object to other Object - c#

I am trying to attach an Projectile to the Player if he gets hit.
Im currently using this code:
transform.SetParent(player.transform);
But this doesn't work as expected.
It seems to follow only movement caused by the Player-Object and not its Rigidbody mean the Projectile will follow this:
transform.position -= transform.right * Time.deltaTime * moveSpeed;
But not this:
rb.AddForce(transform.up * forceMult); or Gravity
So I need a way to make the Projectile also follow the movement caused through the Rigidbody.
Anybody know a way to do this?

To move the arrow and the player via. RigidBody isn't possible from just parenting, because
regarding moving of objects parenting only helps with changing the transform of children if the transform of parent objects changed.
Therefore you should probably get the Arrow Rigidbody and move it via. rb.AddForce() as well.
In public Variables of Player add:
Rigidbody rbArrow;
When you parented the arrow to the player call this function from the player:
transform.SetParent(player.transform);
player.GetArrowRB();
New Function in the Player:
public static void GetArrowRB(){
rbArrow = GetComponentInChildren<RigidBody>();
}
Movement Code:
// Move Player
rb.AddForce(transform.up * forceMult);
// Move Arrow
rbArrow.AddForce(transform.up * forceMult);

Related

I am working on a game project on unity and I am stuck at a camera problem

It has two camera angles. First person for engaging gameplay and top-down for 2D game experience. But in top down camera view I can't figure out the rotation of the camera with respect to player.
I wrote the following script for the main(top-down) camera view.
public class FollowPlayer : MonoBehaviour
{
public GameObject player;
private Vector3 offset = new Vector3(0f, 24.953f, -0f);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
transform.position = player.transform.position + offset;
}
}`
I tried
transform.rotation = player.transform.rotation;
but it didn't work since camera is on top of player. If I could somehow do
transform.rotation = player.transform.rotation + X axis 90 degree;
That would be perfect but I don't know how to do that.
If I understand you correctly, you want to follow the player from above with your second camera. Leaving some flexibility, the best option I think would be Unity's built in Transform.LookAt(target) method (LookAt), which automatically rotates an object (in your case the camera) so that it faces the target.
Therefore, you could do something like this in your Update, assuming your script is attached to the Camera. Otherwise substitute transform with Camera.main.transform:
transform.LookAt(player);
Note: If you plan to have your camera fixed above your player at all times, it is sufficient if you perform the LookAt once, e.g. in Start and then attach the camera as a child to the player. If your camera does not move with your player in the world but you want it to focus the player anyway, do do it in Update. Hope I addressed your problem:)
My problem has been resolved. I was trying to rotate the wrong axis. My bad.
mouseInput = Input.GetAxis("Mouse X");
transform.Rotate(Vector3.forward * speed * -mouseInput);
I needed to get mouse input from user and change the Z-axis according to it. Game is working fine now.

my unity gravity isn't functioning properly, how do I fix it?

I'm new to this, I'm making an obstacle dodging game, and part of the losing conditions is that if the player object falls below -1 on the y axis then the player loses the game, but every time I run the game and intentionally go off the edge of the ground, the player object just floats. I've double checked that the Rigidbody for the player uses gravity, and even checked my scripts for logic errors, nothing has worked. got any ideas on how to fix it?
I've already added the code rb.useGravity = true;
here's the script for the player's movement:
`
using UnityEngine;
public class movement : MonoBehaviour
{
public Rigidbody rb;
public float ForwardMomentum = 1000f
public float SidewaysMomentum = 500f
void FixedUpdate()
{
rb.useGravity = true;
rb.AddForce(0, 0, FowardMomentum * Time.deltaTime);
if (Input.GetKey("d"))
{
rb.AddForce(SidewaysMomentum * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
else if (Input.GetKey("a"))
{
rb.AddForce(-SidewaysMomentum * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
To make a reproducible example for this, all you need to do is:
Add a cube game object (I believe that the box collider and mesh renderer should already be loaded in there)
Add the Rigidbody component and tick use gravity (As well as ticking freeze rotation on the x axis)
Add the new script with the code from above (please fix any errors you find to make it work and let me know how you did it :D)
Add a ground floor and just make it so the player cube is sitting on top of it
then just run it a couple of times and see how it goes, if nothing is out of the ordinary then idk what's going on with my unity
In unity using Rigidbodies is sometimes a bit difficult. But the solutions to these problems come pretty easily.
-Firstly Check if you even have applied a rigidbody (mostlikely you do else your game wouldn't run)
-Check if you have accidently selected "IsKinematic" which could cause your gravity not to be used on that rigidbody.
-Check the way you get the rigidbody in your script, if the script is correctly applied to your gameobject. (if the rigidbody is gotten via the inspector you might need to just drag and drop it into the script)
-Check the collider on your ground if it isn't bigger then the visual

unity falling sprite

So I am trying to figure out how to get my square (sprite) when I click on to fall and collide with my other square (sprite).
I know that I have to write a c# script to get it going with the Method:
private void OnMouseDown(){
}
but I don't know how to change the coordinates in this method please help !
Thanks,
my whole projekt
To change the coordinates of the transform the script is attached to (your player), you must access the transform. If you want to translate it, you should multiply it by Time.deltaTime to ensure that it will remain a constant speed at any framerate.
//On mouse down call
void OnMouseDown(){
//Define your speed
float speed = 1.0f;
//Translate the y position downwards
Vector3 newPos = this.transform.position;
newPos.y -= Time.deltaTime * speed;
this.transform.position.y = newPos.y;
}
However, I'm not sure if you would even want this. It would be a lot better if you set up 2D physics. To do this each object in the scene needs a collider and the player object must have a rigid body. To access these components go to the object and press "Add Component" towards the bottom. Here is an image of the dropdown that will appear:
Then click the highlighted "Physics 2D". Here you want to select "Box Collider 2D" for all the physics game objects and then only "Rigidbody 2D" for the player. When you start the game the 2D player should fall (if done correctly).

How Do I Make a Sprite Look at the Centre of a Scene in Unity2D?

I'm making a game which involves rotating around a point shooting enemies before they reach said point, in 2D. However, as the enemies are going to be spawned in random places around the game, I need to make them rotate towards the centre to start moving in that direction. Here is the code that doesn't function properly:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Rigidbody2D rb;
//this is the enemy, by the way
public Transform follow;
public void Start()
{
transform.LookAt(Vector2.zero);
rb.velocity = follow.up; //'up' worked in my bullet script for heading in the direction the player was facing
}
}
Instead of the knob rotating and slowly moving towards the point, the knob weirdly elongates and then begins to move towards the top of the screen, but at a slight angle. It's probably a stupid mistake, as I've only been writing in C# and using Unity for about a week.
However, any help would be greatly appreciated!
Edit: After clarification, this is my answer:
You should use Vector3.MoveTowards.
void Update ()
{
enemy.transform.position = Vector3.MoveTowards(enemy.transform.position, point.transform.position, speed * Time.deltaTime);
}
I would recommend attaching this to your enemy game object and replacing enemy.transform.position; with gameObject.transform.position;. This way you can make an enemy prefab later on and easily spawn as many as you need.
https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
Sorry if I don't understand fully, but you want the enemys to rotate and move towards the center of the screen?
If so, you can use transform.Rotate(rotation * Time.deltaTime); to rotate the enemys and transform.Translate(vector * Time.deltaTime);to move them towards a point.
Add the game object you want to move to the method. Eg, if this were going to be attached to your enemies script you would write gameObject.transform.Rotate(rotation * Time.deltaTime);.
If you wanted the enemys to circle around something you could create a 'point' game object then attach the rotate script to it. Then make the enemies children of that object so they rotate with it. Then, put the translate script on the enemys so they move towards the point.
Hope this helps!
https://docs.unity3d.com/ScriptReference/Transform-rotation.html
https://docs.unity3d.com/ScriptReference/Transform.Translate.html
Try this. Transform.LookAt might not be working for 2d. See this for similar example.
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Rigidbody2D rb;
public float speed = 1f;
public Transform follow; //this is the enemy, by the way
public void Start()
{
//depending how your enemy points (is its forward direction x axis or y axis) you should either use transform.right or transform.up
transform.right = follow.position - transform.position;
// or use transform.up = follow.position - transform.position;
rb.velocity = transform.right * speed; // change transform.right to transform.up if you use transform.up above.
}
}

Unity rigidbody FixedUpdate basic movement does not work

I'm trying to implement this tutorial on the unity site. I've went over the unity blog and havn't found the solution to my problem there.
I have a simple Rigidbody sphere object over a plane.
The sphere is default sized, and set on: (0,0.5,0).
The plane is also default sized, and set on the origin (0,0,0). Those are the only components I use.
What I'm trying to do is to write a simple C# script behavior for the sphere that will move it across the plane, like so:
public class Controller : MonoBehaviour {
private Rigidbody rb; // Holds the body this script is affecting.
// Called at the start, to set variables.
void Start()
{
rb = GetComponent<Rigidbody>(); // Get the body, if there is one.
}
//For physical changes.
void FixedUpdate()
{
float Horizontal = Input.GetAxis ("Horizontal"); // Get horizontal movement from input.
float Vertical = Input.GetAxis ("Vertical"); // Get vertical movement from input.
Vector3 Movement = new Vector3 (Horizontal, 0.0f, Vertical); // Declaring the movement I'd like to add to the RB. Y axis is irrelevant. X,Z - controlled by user input.
rb.AddForce (Movement); // Making the movement.
}
}
I attached this behavior to the sphere, expecting It'd move when I hit some input key.
Despite this, when I play the project, everything compiles fairly well but the sphere just doesn't move regardless of what I type.
What am I missing?
EDIT: If it's relevant, I also have problems opening the Unity c# code editor (forgot it's name). Whhenever I click open, it just instantly closes. I do everything on Visual Studio.
EDIT 2: My bad, I just figured out I have console Errors. I get the following one:
MissingComponentException: There is no 'Rigidbody' attached to the "Player" game object, but a script is trying to access it.
You probably need to add a Rigidbody to the game object "Player". Or your script needs to check if the component is attached before using it.
UnityEngine.Rigidbody.AddForce (Vector3 force) (at C:/buildslave/unity/build/artifacts/generated/common/modules/NewDynamics.gen.cs:706)
Controller.FixedUpdate () (at Assets/_Scripts/Controller.cs:20)
"Player" is the name I gave the sphere.
I forgot to attach the Rigidbody to the sphere.

Categories