Currently instantiating an object (a prefab) at run time via a button click. The object instantiates each time I click the button but it doesn't move even though I have added force to it.
Checked similar issues where its a mismatch of casting between GameObject and Rigidbody2D but this isn't the issue in my case. Tried switching between transform right and forward multiplied by a large number in case the value was too small for a change which doesn't make a difference either. Any help is appreciated. Thank you.
Following script is on the Player object. The prefab is instantiated from the object 'tip' which is a child object on the Player object. Rigidbody2D is set to Kinematic for bullet.
public Transform tip;
public Rigidbody2D bullet;
if (Input.GetButtonDown("Fire1")) {
Rigidbody2D clone;
clone = Instantiate(bullet, tip.position, Quaternion.identity) as Rigidbody2D;
clone.AddForce(clone.transform.right * 5000000);
}
Rigidbody2D is set to Kinematic for bullet.
This is the mistake: the physics engine never moves Kinematic objects, change the bullet rigidbody body type to Dynamic, and the force you apply with AddForce will move the bullet.
Related
I have a game where map/background is made up of prefabs. My player and prefabs both have rigidbodies and colliders. Neither of them have is trigger checked and the prefabs have collision detection set as continuous dynamic. The player's collision detection is set on continuous. Each of the prefabs have a mesh collider and the individual walls of the prefabs have box colliders (none are set to is trigger). I keep trying to test it on my phone using Unity Remote 5, and every time I move the player it goes through the walls. If anyone has any advice on how to prevent my player from going through the walls, I would really appreciate it!
My movement script is:
public class Movement : MonoBehaviour
{
private Touch touch;
private float speedModifier;
void Start()
{
speedModifier = 0.01f;
}
void Update()
{
if(Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved)
{ transform.position = new Vector3(transform.position.x + touch.deltaPosition.x * speedModifier,
transform.position.y,
transform.position.z + touch.deltaPosition.y * speedModifier);
}
}
}
}
It would really help to see your movement script however it sounds like you are moving player by manipulating transform.position or using rigidbody.MovePosition() without setting isKinematic to true. The documentation says;
If the rigidbody has isKinematic set to false, it works like transform.position=newPosition and teleports the object to the new position (rather than performing a smooth transition).
This behaviour will ignore the collision. Also you don't need rigidbody on every GameObject in the scene. 1 rigidbody on the player is enough to collide it with other objects.
depend on what I got from your question, when you are playing and the player hit the wall, it goes inside; so the problem might be the mass of the wall. if you must add a Rigidbody to the wall so you need to add more mass to the wall also edit the border of the box collider and make them reasonably a bit wider, otherwise if you dont need a rigidbody on the wall simply keep just the box collider and it will works good. hope this answer help you, and it will be better if you can explain more the situation using some pics.
Using the Rigidbody position or applying force tends to cause the Rigidbody to clip through other colliders. I recommend changing rigidbody.velocity instead of directly changing the position.
I'm just starting out with Unity and for my first game I'm trying to make these enemy cubes chase the player. The enemies are spawned at a random position and I'm trying to make them move towards the position of the player cube. But when I try to reference the player's Transform, it won't let me drag it on top, any fixes?
using UnityEngine;
public class enemyFollow : MonoBehaviour {
public Transform player;
public Rigidbody rb;
public float movementForce;
// Update is called once per frame
void FixedUpdate()
{
if (player.position.x > transform.position.x){
rb.AddForce(movementForce * Time.deltaTime,0,0);
}
if (player.position.x < transform.position.x){
rb.AddForce(-movementForce * Time.deltaTime,0,0);
}
if (player.position.z > transform.position.z){
rb.AddForce(0,0,movementForce * Time.deltaTime);
}
if (player.position.z < transform.position.z){
rb.AddForce(0,0,-movementForce * Time.deltaTime);
}
}
}
Unity won't let me drag the player from the gameobjects window onto the script on the prefab. The error says "the variable player of enemyFollow has not been assigned"
It won't let me assign Player.
You can add this in a void Start() method:
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
If I'm understanding correctly, you're trying to assign the player to the enemy in the prefab configuration. That won't work because the prefab isn't in the scene. Since the prefab could be instantiate in any scene, you can't reference scene objects. You need to do it during playtime, unless all the enemies are already in the scene when you're setting it up (in which case you'd need to do it to an instantiated enemy and then copy paste it).
You can use FindGameObjectWithTag() as in Jeff's answer, but make sure to assign a "Player" tag to the player GameObject or prefab.
Another method which I'd recommend would be to have whatever is instantiating the enemies assign their target, that way you don't need to search for a tag with a string you could mistype, and you can just change the reference in one place when you need to change something.
I could really need some help with my GameObjects.
I am working on a game in which I want a pick-up Item to create a Physics Force explosion to blow away the enemies. I made a simple Bomb-Object to test this idea. I added a straightforward code, using a loop to collect all the colliders within its radius, to then addForce to these colliders. Now the code is working properly, but not all my GameObjects are reacting properly.
I looked into why this is, and I noticed that my Collider keeps falling away from the GameObject as soon as I add a RigidBody component to the object. The RigidBody is needed for the AddForce impact. When I remove the rb, the collider stays in place, but the object does not react to the Physics Force.
I added some images to illustrate what I mean:
Image of the Collider of the leaf sinking away..
Example image of objects which DO react to the AddForce.
I already tried to:
Copy/Paste all component settings from the reacting Cube and stone
Gameobjects to the Leaf Gameobject while disabling all other code
such as the c# scripts. The Collider & RB do not fall through the
floor but when Physics Force hits the Collider is blown away while
the GameObject keeps its position.
Try different GameObjects/Collider types.
Removed the water.
Play with amount of force/radius of the bomb.
Edited 'Tag' and 'Layerstyle' of GameObject.
The 'Explosion Code' is added below, however, I don't think the problem is in the code. I added the code to the Main Camera of my scene, and added a simple sphere as the 'bomb' GameObject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Explosion : MonoBehaviour
{
public GameObject bomb; //set the position of the explosion
public float power = 10.0f;
public float radius = 10.0f;
public float upForce = 0.0f;
private void FixedUpdate()
{
if (Input.GetKeyDown("space"))
{
print("space key was pressed");
Invoke("Detonate", 1);
}
}
void Detonate()
{
Vector3 explosionPosition = bomb.transform.position; //set the position of our explosion to the position of the bomb.
Collider[] colliders = Physics.OverlapSphere(explosionPosition, radius); //collects all colliders within the radius.
foreach (Collider hit in colliders) { //for each individual collider the following code is ran.
Rigidbody rb = hit.GetComponent<Rigidbody>(); //declare'rb' rigidbody. Get rb component from each collider
if (rb != null)
{
print("BOOM!");
rb.AddExplosionForce(power, explosionPosition, radius, upForce, ForceMode.Impulse); //add force to each collider
}
}
}
}
How do I make the Rigidbody, Collider and GameObject of the leaf hold onto each other like the standard 3D object 'cube', so that I can make these blow away with the Physics Force just like the other models?
Thank you for your time, I have been trying things and looking around on the Internet for hours now but can't seem to find any solution.
What happens if you add the rigidbody in stop mode and press play? Does it move away in a similar manner? This may, and is expected to happen, if your colliders intersect with each other. As soon as you add a rigidbody, they find themselves trapped in a serious collision.
If you don't want to modify the scene, you can fiddle with the collision matrix in project settings / physics
I have a cube tagged "player", which needs to jump at certain locations, represented by Empty GameObjects.
I want to make a point system and that why I put on some of the places other game objects tagged "Coin"
The cube has an animation which plays each time it moves to another point recognized by clicking with the mouse on it.
When I jump on the coin location I want the Coin object to get destroyed.
I use this function:
void OnTriggerEnter(Collider col){
if (col.gameObject.tag == "Coin") {
Debug.Log ("Plm");
stroy (col.gameObject);
}
The problem is that when I'm jumping at the Coin location nothing happens.
I have box colliders on both objects and OnTrigger checked on both.
1) Make sure one gameobject has a rigidbody
To have the OnTriggerEnter happen you need at least one of the two object to have a RigidBody attached to it.
2) Static Trigger Collider
An object that has a collider and isTrigger checked but no rigibBody is considered a Static Trigger Collider which are From Unity Documentation:
This is a GameObject that has a Collider but no Rigidbody. Static colliders are used for level geometry which always stays at the same place and never moves around. Incoming rigidbody objects will collide with the static collider but will not move it.
This type of collider interactions is perfect for your coins because they do not move and stay static.
3) Rigidbody Trigger Collider
The next type of collider interactions is a Rigidbody Trigger Collider which are :
This is a GameObject with a Collider and a normal, non-kinematic Rigidbody attached. Rigidbody colliders are fully simulated by the physics engine and can react to collisions and forces applied from a script. They can collide with other objects (including static colliders)
This type of collider is what you need on your player and as it says in the Unity Documentation it will be able to collide with the Static trigger collider.
Important observation:
Having IsTrigger set to true on your player collider will cause your player to not respond as a solid object
A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object and will simply allow other colliders to pass through.
which might not be the most optimal solution for you because most of the time you want your player to be able to collide with other things like the ground. So you can set the isTrigger to false and just have a rigidbody on you player and it will react to the coins if they're set as Static Trigger Collider.
If you want an easy way to know what can collide with what Read the colliders documentation and take a look at this chart that shows it in a more simpler way.
I'm trying to make a magnet PowerUp in Unity. I used this script, which I attached to the coin GameObject:
public GameObject attractedTo;
private float strengthOfAttraction = 3f;
void FixedUpdate ()
{
Vector3 direction = attractedTo.transform.position - transform.position;
gameObject.GetComponent<Rigidbody>().AddForce (strengthOfAttraction * direction);
}
I have two problems :
1. Only newly spawn coins are attracted to the player
2. For some reason, the coins move only in straight lines, so most of them goes past the player
Anyone knows how this can be fixed?
Any help will be appreciated!
Major issue on your code. You have to recreate your procedure logic on how you make the coins get closer to the Player.
First Major problem is this.
void FixedUpdate() So on a fix amount of time per frame. You are trying to
Declare a Variable Vector3 : Vector3 direction = attractedTo.transform.position - transform.position;
So frame will recalculate and create a new pointer name direction then you try to find gameObject.GetComponent<Rigidbody>().AddForce (strengthOfAttraction * direction);
your Own Component in your gameObject. Then Call Addforce. AddForce. And you didn't even use time.deltatime.
Addforce Will push the rigidbody depending on the direction you input. So it will go straight. And you are doing this Every Fix amount of frame per sec.
First fix your procedure. My recommendation is this.
Use the Smooth Follow script. Made by Unity3D get your Reference there. It is also installed already in the script section in your Editor. If you are having problem finding it, go to this link and check he script.
Smooth Follow Script
[Update Answer]
For the 2nd Problem that only new coins is getting attracted.
Check all of this situations.
Your Player is newly spawned and your attractedTo variable is blank.
Non newly spawned coins should have referenced to the Player already, if not you have to tell all the coins that if you spawn the Player, they needed to be attracted to Player. -> Assign attractedTo when Player Spawned.
You can either Achieve that on Instantiate then find all GameObjects with TAG. Then getcomponent then assign attractedTo
Your non Spawned coins, doesn't have the Script Component.
Your non Spawned coins, is disabled.