transform.position not setting correct position in Unity? - c#

I am having this problem that I don't know how to solve, I have a moving object that return to a position if a condition is verified, but it seems like it is working sometimes, but sometimes it is not ..
Here is my script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingDes : MonoBehaviour {
private float speed = 5f;
Transform trn;
//-37.6914
//62.32123
// Use this for initialization
void Start() {
trn = GetComponent<Transform>();
}
// Update is called once per frame
void Update() {
transform.Translate(Vector3.back * (speed * Time.deltaTime));
if(transform.position.z <= -37.6914){
Vector3 newPosition = new Vector3(17.5f,125.7f,165.32123f);
trn.position = newPosition;
}
}
}
The problem is that I can see in my Unity editor that the position is different from what I have set, and I don't understand from Where those values came from, I did not write them for sure.
Any help would be much appreciated.

You are moving object with transform.Translate every frame, so immediately after setting up new position, your object is moved again. Notice that in your case trn, and transform, refers to the same Transform component.

Why don't you change your trn.position= to transform.position= I don't think you need GetComponent<> for transform component of the current gameObject. Or maybe related to relativeTo parameter of .Translate method.

Related

Unity, how find my game object and move it

I'm totally newbie with Unity and C# and i try to do a 3D game.
I want to when i press "Qkey", the cube descends in height.
here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ripcube : MonoBehaviour
{
// Start is called before the first frame update
bool isTeleported = false;
// Update is called once per frame
void Update()
{
if (Input.GetKey("a") && !isTeleported)
{
ripcube.transform.position = (-2, -2, -2) ;
}
}
}
And it gives me the error:
(19,13): error CS0120: An object reference is required for the non-static field, method, or property 'Component.transform'
I know than ripcube is my class, but what is my gameobject? i created my cube on the graphics interface..
Thanks for your help
You should go watch some basic videos on youtube on how unity gameobjects work but for now:
You can reference game objects from your code or find them as following:
public class ripcube: MonoBehaviour
{
GameObject myCubeObject;
float speed = 2f;
void Start()
{
myCubeObject = GameObject.Find("YourCubeNameInUnity");
}
void Update()
{
if(Input.GetKey(KeyCode.Q))
{
myCubeObject.transform.Translate(speed * Vector3.down * Time.deltaTime);
}
}
}
Thing you should notice here :
The GameObject is a Unity class that is the base for all the game objects in the scene,
you can find it by its name in the Hierarchy view.
After you find it you can access it in the Update() function and change its transform every frame.
Here I used Translate wich is an addition to the position every frame
you can also use myCubeObject.transform.position += speed * Vector3.down * Time.deltaTime
Be aware that im using a float speed variable that is the speed the cube will go in the desired direction (I used 2 for the value but it can be anything really).
The direction is specified by a vector (Vector3.down). You can change is as you please
Multiplying by Time.deltaTime makes the movement independant on FPS (Frames per second) wich is determined normally bt the machine the game is running on.
bro you can use
transform.position = new Vector3(-2, -2, -2);
instead of
transform.position = (-2, -2, -2) ;
and change
Input.GetKey("a")
to
Input.GetKey(KeyCode.Q)

How to make this gameobject instantiated as a child of a parent gameobject be positioned at an offset?

I've followed a C# in Unity tutorial to create a simple Space Invaders game. I'm now trying to understand the different functions being used.
There is this class called PlayerController. It also defines a shot gameobject, a field which is then supplied with a bullet prefab:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Transform player;
public float speed;
public float maxBound, minBound;
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
private float nextFire;
// Start is called before the first frame update
void Start()
{
player = GetComponent<Transform> ();
}
// Update is called once per frame
void FixedUpdate()
{
float h = Input.GetAxis ("Horizontal");
if (player.position.x < minBound && h < 0)
h = 0;
else if (player.position.x > maxBound && h > 0)
h = 0;
player.position += Vector3.right * h * speed;
}
void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
}
}
}
The bullet gameobject used the class BulletController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour
{
private Transform bullet;
public float speed;
// Start is called before the first frame update
void Start()
{
bullet = GetComponent<Transform>();
}
void FixedUpdate()
{
bullet.position += Vector3.up * speed;
if (bullet.position.y >= 10)
Destroy(gameObject);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Enemy")
{
Destroy(other.gameObject);
Destroy(gameObject);
PlayerScore.playerScore++;
}
else if (other.tag == "Base")
Destroy(gameObject);
}
}
From what I understand, a Transform object has values for position, rotation and scale.
So first, what does declaring x = GetComponent; do?
Second, where does "shotSpawn" takes its values from? From the object to which the code is applied to?
Third, the bullet gets instantiated exactly at the center of the square serving as the player ship's body, but I want it start higher at the y axis so it starts at the end of the cannon shape. It also seems to graphically intersect with the ship's body, so I wanted to move it slightly into the z axis. So how can you write that? I tried adding to the value of shotSpawn.position but it keeps declaring errors.
Thanks in advance.
A GetComponent means basically just grabbing a component of an object. Take a simple example: The Main Camera has a lot of components:
1.1. A Transform component. This component is used, as you understood, to define the position, rotation and scaling of an object
1.2. A Camera component. This has plenty of fields
1.3. A Flare Layer component.
etc.
These components can be grabbed via script. The reason developers use this is for their properties. For example, by saying Transform playerTransformComp = player.GetComponent<Transform>();, you will be able to write playerTransformComp.position. position is a property of objects of type Transform.
I don't think that the GetComponent you saw in the tutorial are useful because every game object has a transform component anyway, so if they declared the player as public GameObject player;, then used player.transform.position instead, it would have been way easier. In fact, I don't think it even makes sense to declare something as Transform, and then grabbing the Transform component. As #BugFinder said in your previous post, the tutorial is pretty bad overall.
shotSpawn takes its values from... itself! It is a public object, so I'm assuming you dragged & dropped the shotSpawn object from the scene into the script's fields. This means that the shotSpawn object from the script is the object you dragged & dropped on the script's fields. You can use all of its features and the dragged & dropped object will be affected. Thus, you can use shotSpawn.position and shotSpawn.rotation. I might be repeating myself here for a little bit, but please notice that shotSpawn is a Transform object, therefore you can use a typical Transform object's properties.
The documentation on Transform.position (as well as the one on Transform.rotation say you have to use Vector3 objects to add or substract values to them.
One would do shotSpawn.position + new Vector3(10f, 5f, 10f).
Naturally, you can also do
value = new Vector3(10f, 5f, 10f);
and then Instantiate(shot, shotSpawn.position + value, shotSpawn.rotation);
Also, please (for the future), try to ask one question per post, otherwise people will ignore your question or even flag it and it will be deleted. I was once like you, so I wouldn't do that, but please take this into consideration when making further posts.

My function runs as soon as I apply the script to a GameObject in scene editor. I need it to only affect the object at runtime

I have a simple script that should grab a GameObject's transform position and rotation then move the GameObject back to that position when it's hit by a Raycast. (Objects get moved around as the player bumps into them).
Its working fine for the objects that already have the script attached but when I apply the script to a new GameObject, it resets the transform's values to (0,0,0),(0,0,0) in the scene editor.
I'm sure there's a smarter way to do this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TransformReset : MonoBehaviour
{
private Transform LocalTransform;
private Vector3 InitialPos;
private Quaternion InitialRot;
private Vector3 CurrentPos;
private Quaternion CurrentRot;
void Start()
{
InitialPos = transform.position;
InitialRot = transform.rotation;
}
public void Reset()
{
transform.position = InitialPos;
transform.rotation = InitialRot;
Debug.Log("resetting position of " + gameObject.name);
}
}
that "public void Reset()" part is called by my raycasting script. But I think the problem is that its running in the scene editor before ever getting a useful "InitialPos" value.
Appreciate any help and advice.
Reset is a MonoBehaviour Message that the engine calls under certain conditions. From the documentation, emphasis mine:
Reset is called when the user hits the Reset button in the Inspector's
context menu or when adding the component the first time. This
function is only called in editor mode. Reset is most commonly used to
give good default values in the Inspector.
Basically, your naming of the method is colliding with built in behaviour it shouldn't have anything to do with. If you change the name of your method to something else, it should work fine:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TransformReset : MonoBehaviour
{
private Transform LocalTransform;
private Vector3 InitialPos;
private Quaternion InitialRot;
private Vector3 CurrentPos;
private Quaternion CurrentRot;
void Start()
{
InitialPos = transform.position;
InitialRot = transform.rotation;
}
public void ResetTransform()
{
transform.position = InitialPos;
transform.rotation = InitialRot;
Debug.Log("resetting position of " + gameObject.name);
}
}
And then in the other class:
transformResetComponent.ResetTransform();

Projectile in Unity 2D

I'm attempting to learn Unity (so please forgive my newbie-ness). I've set up my project as 2d, got a sprite moving about and I'm trying to get a projectile firing (I appreciate there are MANY SO q's about such, but I just can't get it to work, after trying many solutions). I'm a complete nub when it comes to physics!
Here's my very simple script:
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
public Transform mObject;
public Transform mProjectile;
public Vector2 mProjectileSpeed = new Vector2 (10f, 10f);
public Vector2 mSpeed = new Vector2(15, 15);
private Vector2 mMovement;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float inputX = Input.GetAxis("X");
float inputY = Input.GetAxis("Y");
mMovement = new Vector2 (mSpeed.x * inputX, mSpeed.y * inputY);
if (Input.GetButton ("Fire1"))
Shoot ();
}
void Shoot(){
GameObject clone = (GameObject)Instantiate (mProjectile, rigidbody2D.transform.position, Quaternion.identity);
clone.rigidbody2D.velocity = (clone.transform.forward * 1000);
}
void FixedUpdate(){
rigidbody2D.velocity = mMovement;
}
}
And this is what it's doing:
No force is being added to the instantiated object and it shoots out both sides of my sprite, which I just don't understand at all.
I did find a solution on the Unity answers site that said to IgnoreCollider just in case the two box colliders were conflicting results, but it didn't make a difference.
I'm sure I'm doing something completely stupid, but how can I do this?
Many thanks!
Try using Addforce() method,
something like this :
gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime);
or
gameObj.rigidbody2D.AddForce(transform.forward * 100);
or
gameObj.rigidbody2D.AddForce(Vector3.up * 1000);
See which combination and what values matches your requirement and use accordingly. Hope it helps
As #maZZZu said, Instantiate your projectile sprites ahead of your character so that your character and projectiles may not collide.
Secondly, clone.rigidbody2D.velocity = (clone.transform.forward * 1000); part of your code will only allow the projectile to move in forward direction (x-axis in case to 2D and z-axis in 3D). Try using mMovement instead (if you want it to move in other directions as well). e.g. clone.rigidbody2D.velocity = (mMovement * 1000);

Unity C# - Rigidbody.AddForce not working as intended

So, I am trying to make a cube move with the WSAD buttons and for some reason, even though I am not touching any buttons, it moves diagonally up and to the left. I am using Unity 4.5.1
Code:
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public float moveSpeed;
private Vector3 input;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
input = new Vector3(Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
print(input);
}
}
Your problem may be somewhere else, because the code seems just fine. If I were you, I'd try to take a look to this page. You might find the solution to this issue

Categories

Resources