- Home /
Rigid Body Velocity in C#
Hey all got a small problem. I am writing a movement script for my main character in C#. Here is what I have so far...
using UnityEngine;
using System.Collections;
public class MainPlayer : MonoBehaviour {
private int health; private int boards; private int nails;
// Use this for initialization void Start () {
}
// Update is called once per frame void Update () {
gameObject.transform.position.y = -15;
gameObject.rigidbody.freezeRotation = true;
if( Input.GetKey( "a" ) ) // move left
{
gameObject.rigidbody.velocity.x = -8;
}
}
}
I am getting these errors: Cannot modify the return value of UnityEngine.Transform.position' because it is not a variable Cannot modify the return value of
UnityEngine.Rigidbody.velocity' because it is not a variable
After reading around I figured its because of the struct class difference that C# seems to have. How would I go about resolving this problem? Thanks for any help :)
Answer by Wolfram · Feb 26, 2010 at 11:32 AM
You cannot assign to individual elements of transform.position, only the whole object. So instead, you need to do one of the following:
gameObject.transform.position=new Vector3(gameObject.transform.position.x,
-15,
gameObject.transform.position+z);
or
Vector3 newpos=gameObject.transform.position;
newpos.y=-15;
gameObject.transform.position=newpos;
For relative movements, you can do:
gameObject.transform.position=gameObject.transform.position+new Vector3(0,-15,0);
or use the convenience methods:
gameObject.transform.Translate(new Vector3(0,-15,0), Space.World);
The same goes for velocity and others.
For a more detailed discussion, check out http://forum.unity3d.com/viewtopic.php?t=6900
Answer by Brian-Kehrer · Feb 26, 2010 at 02:26 AM
Velocity is a vector3, which is a struct.
The only way to assign to a Vector3 is by assigning the whole thing:
gameObject.transform.position = new Vector3(
gameObject.transform.position.x,
-15,
gameObject.transform.position.z);
The data type is the same, the only difference is in Unityscript (javascript) they have included some helper functions which does this for you.
Answer by Milad · Feb 26, 2010 at 10:17 AM
what do u want to do exactly?translate/position/velocity?
translate: transform.translate(vector3.right*amttomove*Time.deltatime);
Velocity: transform.rigidbody.velocity=transform.transformdirection(0,0,speed);
yourself correct the uppercase and lowercase.
good luck.
Answer by jonathan dinero · May 08, 2016 at 08:56 PM
que librería se necesita para usar un Addforce por que no funciona en un juego de unity con el comondo rigidbody.AddForce(movement, ForceMode.Force);