private void INTERNAL_get_motor(out JointMotor value){}
private void INTERNAL_set_motor(ref JointMotor value){}
public override void UpdateFinger() { bool oldColliding = colliding; //See whether we should enable motor joints this frame checkColliding(); if (colliding && !oldColliding) { timeOfCollision = Time.fixedTime; } for (int i = 0; i < bones.Length; ++i) { if (bones[i] != null) { // Set bone dimensions. CapsuleCollider capsule = bones[i].GetComponent <CapsuleCollider>(); if (capsule != null) { // Initialization capsule.direction = 2; bones[i].localScale = new Vector3(1f / transform.lossyScale.x, 1f / transform.lossyScale.y, 1f / transform.lossyScale.z); // Update capsule.radius = (GetBoneWidth(i) / 2f) * transform.lossyScale.x; capsule.height = (GetBoneLength(i) + GetBoneWidth(i)) * transform.lossyScale.x; } Rigidbody boneBody = bones[i].GetComponent <Rigidbody>(); //Initialize Hand! if (dirty) { bones[i].gameObject.SetActive(true); if (boneBody) { boneBody.velocity = Vector3.zero; boneBody.angularVelocity = Vector3.zero; bones[i].position = GetBoneCenter(i); bones[i].rotation = GetBoneRotation(i); } else { bones[i].position = GetBoneCenter(i); bones[i].rotation = GetBoneRotation(i); } } else { //Move Joint Motors! if (usingConstraints || useConstraints) { if (i == 1) { Quaternion localRealFinger = (Quaternion.Euler(180f, 180f, 180f) * (Quaternion.Inverse(PalmRot * origPalmToJointRotation) * GetBoneRotation(i))); if (rootJoint) { if (fingerType == Finger.FingerType.TYPE_THUMB && hand_.IsRight) { localRealFinger = Quaternion.Euler(localRealFinger.eulerAngles.y, localRealFinger.eulerAngles.x, localRealFinger.eulerAngles.z); } else if (fingerType == Finger.FingerType.TYPE_THUMB && hand_.IsLeft) { localRealFinger = Quaternion.Euler(localRealFinger.eulerAngles.y * -1f, localRealFinger.eulerAngles.x * -1f, localRealFinger.eulerAngles.z); } else { localRealFinger = Quaternion.Euler(localRealFinger.eulerAngles.x * -1f, localRealFinger.eulerAngles.y, 0f); } rootJoint.targetRotation = localRealFinger; } } if (hinges != null && hinges[i - 1] != null && hinges[i - 1].GetType().Equals(typeof(HingeJoint))) { if (timeOfCollision == Time.fixedTime) { boneBody.velocity = Vector3.zero; } Quaternion localRealFinger = (Quaternion.Inverse(GetBoneRotation(i - 1)) * GetBoneRotation(i)); Quaternion localPhysicsFinger = (Quaternion.Inverse(bones[i - 1].rotation) * bones[i].rotation); float offset = (Quaternion.Inverse((Quaternion.Inverse(localRealFinger) * localPhysicsFinger))).eulerAngles.x; if (offset > 180) { offset -= 360f; } JointMotor mmotor = new JointMotor(); mmotor.force = 50000f; // FingerStrength; mmotor.targetVelocity = offset * -50f; // FingerSpeed; mmotor.freeSpin = false; ((HingeJoint)hinges[i - 1]).motor = mmotor; } Vector3 transformedBonePos = GetBoneCenter(i); //Vector3 transformedBonePos = bones[i - 1].TransformPoint(Quaternion.Inverse(GetBoneRotation(i - 1)) * (GetBoneCenter(i) - GetBoneCenter(i - 1))); //Vector3 deltaToPrevBone = bones[i].position - bones[i-1].position; if (!detach) { Vector3 deltaVel = ((transformedBonePos - bones[i].position) / Time.fixedDeltaTime); //deltaVel = Vector3.Lerp(boneBody.velocity, deltaVel, 1f); boneBody.velocity = deltaVel.magnitude > 2f ? (deltaVel / deltaVel.magnitude) * 2f : deltaVel; } //Set Velocity! } else { Vector3 deltaVel = ((GetBoneCenter(i) - bones[i].position) / Time.fixedDeltaTime); //deltaVel = Vector3.Lerp(boneBody.velocity, deltaVel, 1f); //boneBody.velocity = deltaVel.magnitude > 2f ? (deltaVel / deltaVel.magnitude) * 2f : deltaVel; /* * if (i > 1) { * Vector3 transformedBonePos = bones[i - 1].TransformPoint(Quaternion.Inverse(GetBoneRotation(i - 1)) * (GetBoneCenter(i) - GetBoneCenter(i - 1))); * Vector3 deltaVel = ((transformedBonePos - bones[i].position) / Time.fixedDeltaTime); * //Vector3 deltaVel = ((GetBoneCenter(i) - bones[i].position) / Time.fixedDeltaTime); * boneBody.velocity = deltaVel.magnitude > 3f ? (deltaVel / deltaVel.magnitude) * 3f : deltaVel; * } else { * Vector3 transformedBonePos = Palm.transform.TransformPoint(Quaternion.Inverse(PalmRot) * (GetBoneCenter(i) - PalmPos)); * Vector3 deltaVel = ((transformedBonePos - bones[i].position) / Time.fixedDeltaTime); * //Vector3 deltaVel = ((GetBoneCenter(i) - bones[i].position) / Time.fixedDeltaTime); * boneBody.velocity = deltaVel.magnitude > 3f ? (deltaVel / deltaVel.magnitude) * 3f : deltaVel; * } */ /* * Quaternion boneRot = GetBoneRotation(i); * float dot = Quaternion.Dot(boneBody.rotation, boneRot); * if (dot > 0f) { boneRot = new Quaternion(-boneRot.x, -boneRot.y, -boneRot.z, -boneRot.w); } * Vector3 axis; float angle; * Quaternion localQuat = boneBody.rotation * Quaternion.Inverse(boneRot); * localQuat.ToAngleAxis(out angle, out axis); * axis *= angle; * if ((axis / Time.fixedDeltaTime).x != Mathf.Infinity && (axis / Time.fixedDeltaTime).x != Mathf.NegativeInfinity && float.IsNaN((axis / Time.fixedDeltaTime).x)) { * boneBody.angularVelocity = (axis / Time.fixedDeltaTime); * } */ boneBody.MoveRotation(GetBoneRotation(i)); if (Time.fixedTime - timeOfCollision > resetPeriod && colliding) { boneBody.MovePosition(GetBoneCenter(i)); } } } } } if (Time.fixedTime - timeOfCollision > resetPeriod && colliding) { timeOfCollision = Time.fixedTime; } if (dirty) { dirty = false; Palm.transform.position = PalmPos; Palm.transform.rotation = PalmRot; if (usingConstraints || useConstraints) { InitializeFingerJoints(); } } }
void setAngles(HingeJoint joint, float ang, float speed) /// <summary> /// This class moves a single joint to the passed angle /// at a specified speed. The angles are defined in the /// same way as in the Nao interface. Speed will also be, /// but currently is not. /// <\summary> { /// direction sets motion to be clockwise or anti float direction = 1; /// Some angles have to be changed because of how /// Nao defines its angles /// Also, set the speed to be in degrees per second if (joint == rightShoulder) { ang += 40; speed *= 427.2f; } else if (joint == rightElbow) { ang *= -1; ang = 180 - ang; speed *= 370.6f; } else if (joint == rightHip) { ang = 180 + ang; speed *= 380.6f; } else if (joint == rightAnkle) { ang *= -1; ang = 90 - ang; speed *= 380.6f; } else if (joint == Neck) { ang *= -1; ang += 90; speed *= 370.6f; } else { speed *= 380.6f; } for (int i = 0; i < 6; i++) /// Set the angle in the list allAngles to the correct limit angle { if (joint == allJoints[i]) { allAngles[i] = ang; } } /// Turn off joint limits temporarily joint.useLimits = false; /// Define a motor for the joint JointMotor motor = joint.motor; if (ang < joint.angle + 90) /// Determine direction of rotation { direction = -1; } /// Set the motor velocity, and switch the motor on motor.targetVelocity = speed * direction; joint.motor = motor; joint.useMotor = true; }
public void SetTargetVelicty(int targetVelocity) { this.targetVelocity = targetVelocity; this.motor.targetVelocity = targetVelocity; this.joint.motor = this.motor; }
// Update is called once per frame void FixedUpdate() { GameObject CGA_Library_capsule = GameObject.Find("CGA Library"); DeltaRobotClass DeltaRobotFile = CGA_Library_capsule.GetComponent <DeltaRobotClass> (); DeltaRobot theRobot = DeltaRobotFile.Robot1; currentposition = (1f / 3f) * (Platform_D.transform.position + Platform_F.transform.position + Platform_E.transform.position - Base_A.transform.position - Base_B.transform.position - Base_C.transform.position); end_point_error = theRobot.end_point - currentposition; if (use_spring == true && use_motor == false) { GameObject CGA_Model_Manager = GameObject.Find("CGA Model Manager"); ArmDemo2 ArmFrame = CGA_Model_Manager.GetComponent <ArmDemo2> (); float Angle_A = ArmFrame.Angle_A; JointSpring sprA = hingeA.spring; sprA.targetPosition = -Angle_A + 36.87f; sprA.spring = springConst; sprA.damper = damperConst; hingeA.spring = sprA; hingeA.useSpring = use_spring; float Angle_B = ArmFrame.Angle_B; JointSpring sprB = hingeB.spring; sprB.targetPosition = -Angle_B + 36.87f; sprB.spring = springConst; sprB.damper = damperConst; hingeB.spring = sprB; hingeB.useSpring = use_spring; float Angle_C = ArmFrame.Angle_C; JointSpring sprC = hingeC.spring; sprC.targetPosition = -Angle_C + 36.87f; sprC.spring = springConst; sprC.damper = damperConst; hingeC.spring = sprC; hingeC.useSpring = use_spring; } else if (use_spring == false && use_motor == true) { float[] dtheta_dt_l = theRobot.dtheta_dt_l; // float[] dtheta_dt_l=new float[]{0,0,0}; float k_p0 = 700f; float k_p = 70f; float k_d = 0f, k_i = 0f; Vector3 derivative_error = end_point_error - last_error; accum_error += end_point_error; Vector3 input_velocity = k_p * end_point_error + k_d * derivative_error + k_i * accum_error; // Vector3 input_velocity= k_p*end_point_error; float [,] inv_jacob = theRobot.differential_inverse_kinematics(); // for(int i=0;i<3;i++){ // dtheta_dt_l[i]=inv_jacob[i,0]*input_velocity.x+inv_jacob[i,1]*input_velocity.y+inv_jacob[i,2]*input_velocity.z; // } HingeMoterVelocityA = k_p0 * dtheta_dt_l[0]; hingeA.useSpring = false; hingeA.useMotor = true; JointMotor temp_motor = hingeA.motor; temp_motor.force = unified_motor_force; temp_motor.targetVelocity = HingeMoterVelocityA; temp_motor.freeSpin = true; hingeA.motor = temp_motor; HingeMoterVelocityB = k_p0 * dtheta_dt_l[1]; // ConfigHingeJoint_usingMotor(hingeB, HingeMoterVelocityB, unified_motor_force); hingeB.useSpring = false; hingeB.useMotor = true; temp_motor = hingeB.motor; temp_motor.force = unified_motor_force; temp_motor.targetVelocity = HingeMoterVelocityB; temp_motor.freeSpin = true; hingeB.motor = temp_motor; HingeMoterVelocityC = k_p0 * dtheta_dt_l[2]; // ConfigHingeJoint_usingMotor(hingeC, HingeMoterVelocityC, unified_motor_force); hingeC.useSpring = false; hingeC.useMotor = true; temp_motor = hingeC.motor; temp_motor.force = unified_motor_force; temp_motor.targetVelocity = HingeMoterVelocityC; temp_motor.freeSpin = true; hingeC.motor = temp_motor; } if (use_limit == true) { foreach (HingeJoint HingeX in UpperArmHingeJointList) { ConfigHingeJoint_limit(HingeX, limit_min, limit_max, limit_bounciness, limit_bounceMinVelocity); } } updateRigidBodyParam(UpperArmRBList, upper_arm_mass, drag, angular_drag, use_gravity); updateRigidBodyParam(ElbowJointList, elbow_mass, drag, angular_drag, use_gravity); updateRigidBodyParam(LowerArmList, lower_arm_mass, drag, angular_drag, use_gravity); updateRigidBodyParam(PlatformRBList, platform_mass, drag, angular_drag, use_gravity); last_error = end_point_error; }
// Use this for initialization void Start() { m = new JointMotor(); }
public void SetForce(int force) { this.force = force; this.motor.force = force; this.joint.motor = this.motor; }
// Drive All Motors Associated with a PWM port public static void UpdateAllMotors(RigidNode_Base skeleton, unityPacket.OutputStatePacket.DIOModule[] dioModules) { float[] pwm = dioModules [0].pwmValues; float[] can = dioModules [0].canValues; if (Input.anyKey) { pwm [0] += (Input.GetKey(KeyCode.UpArrow) ? speedArrowPWM : 0.0f) + (Input.GetKey(KeyCode.DownArrow) ? -speedArrowPWM : 0.0f) + (Input.GetKey(KeyCode.LeftArrow) ? -speedArrowPWM : 0.0f) + (Input.GetKey(KeyCode.RightArrow) ? speedArrowPWM : 0.0f); pwm [1] += (Input.GetKey(KeyCode.UpArrow) ? -speedArrowPWM : 0.0f) + (Input.GetKey(KeyCode.DownArrow) ? speedArrowPWM : 0.0f) + (Input.GetKey(KeyCode.LeftArrow) ? -speedArrowPWM : 0.0f) + (Input.GetKey(KeyCode.RightArrow) ? speedArrowPWM : 0.0f); } List <RigidNode_Base> listOfSubNodes = new List <RigidNode_Base>(); skeleton.ListAllNodes(listOfSubNodes); foreach (RigidNode_Base node in listOfSubNodes) { UnityRigidNode uNode = (UnityRigidNode)node; //Debug.Log(uNode.GetSkeletalJoint().cDriver == null); } // Cycles through the packet for (int i = 0; i < pwm.Length; i++) { foreach (RigidNode_Base node in listOfSubNodes) { // Typcasting RigidNode to UnityRigidNode to use UnityRigidNode functions UnityRigidNode unitySubNode = (UnityRigidNode)node; if (unitySubNode.GetSkeletalJoint() != null && unitySubNode.GetSkeletalJoint().cDriver != null && unitySubNode.GetSkeletalJoint().cDriver.isCan) { pwm = can; } // Checking if there is a joint (and a joint driver) attatched to each joint if (unitySubNode.GetSkeletalJoint() != null && unitySubNode.GetSkeletalJoint().cDriver != null && unitySubNode.GetSkeletalJoint().cDriver.GetDriveType().IsMotor()) { // If port A matches the index of the array in the packet, (A.K.A: the packet index is reffering to the wheelCollider on the subNode0), then that specific wheel Collider is set. if (unitySubNode.HasDriverMeta <WheelDriverMeta>() && unitySubNode.GetSkeletalJoint().cDriver.portA == i + 1) { float OzInToNm = .00706155183333f * Init.PHYSICS_MASS_MULTIPLIER; BetterWheelCollider bwc = unitySubNode.unityObject.GetComponent <BetterWheelCollider>(); bwc.currentTorque = OzInToNm * (pwm [i] * 271.1f); bwc.brakeTorque = 343f * OzInToNm; } else if (unitySubNode.GetSkeletalJoint().cDriver.portA == i + 1) { Joint joint = unitySubNode.GetJoint <Joint>(); // Something Arbitrary for now. 4 radians/second float OzInToNm = (.00706155183333f / 3f) * Init.PHYSICS_MASS_MULTIPLIER; float motorForce = OzInToNm * (Math.Abs(pwm [i]) < 0.05f ? 343f : (pwm [i] * pwm [i] * 171.1f)); float targetVelocity = 10000f * Math.Sign(pwm [i]); #region Config_Joint if (joint != null && joint is ConfigurableJoint) { ConfigurableJoint cj = (ConfigurableJoint)joint; JointDrive jD = cj.angularXDrive; jD.maximumForce = motorForce; cj.angularXDrive = jD; cj.targetAngularVelocity = new Vector3(targetVelocity, 0, 0); // We will need this to tell when the joint is very near a limit float angularPosition = GetAngleBetweenChildAndParent(unitySubNode); // Stopping the configurable joint if it approaches its limits (if its within 5% of its limit) if (cj.angularXMotion == ConfigurableJointMotion.Limited && (cj.highAngularXLimit.limit - angularPosition) < (0.05f * cj.highAngularXLimit.limit)) { // This prevents the motor from rotating toward its limit again after we have gotten close enough to the limit that we need to stop it. // We will need it to be able to rotate away from the limit however (hence, the if-else statements) // If the local up Vector of the unityObject is negative, the joint is approaching its positive limit (I am not sure if this will work in all cases, so its testing time!) if (unitySubNode.unityObject.transform.up.x < 0 && cj.targetAngularVelocity.x > 0) { cj.targetAngularVelocity = Vector3.zero; } else if (unitySubNode.unityObject.transform.up.x > 0 && cj.targetAngularVelocity.x < 0) { cj.targetAngularVelocity = Vector3.zero; } } } #endregion #region hinge joint if (joint != null && joint is HingeJoint) { HingeJoint hj = (HingeJoint)joint; JointMotor motor = hj.motor; motor.force = motorForce; motor.freeSpin = false; motor.targetVelocity = targetVelocity; if (hj.useLimits) { float limitRange = hj.limits.max - hj.limits.min; if (Math.Min(Math.Abs(hj.angle - hj.limits.min), Math.Abs(hj.angle - hj.limits.max)) < 0.05 * limitRange) { // This prevents the motor from rotating toward its limit again after we have gotten close enough to the limit that we need to stop it. // We will need it to be able to rotate away from the limit however (hence, the if-else statements) // If the local up Vector of the unityObject is negative, the joint is approaching its positive limit (I am not sure if this will work in all cases, so its testing time!) if (unitySubNode.unityObject.transform.up.x < 0 && motor.targetVelocity > 0) { motor.targetVelocity = 0; } else if (unitySubNode.unityObject.transform.up.x > 0 && motor.targetVelocity < 0) { motor.targetVelocity = 0; } } } hj.motor = motor; #endregion } else if (unitySubNode.GetSkeletalJoint().cDriver.portA == i + 1) { // Should we throw an exception here? Debug.Log("There's an issue: We have an active motor not set (even though it should be set)."); } } } /* if(unitySubNode.GetSkeletalJoint().cDriver.GetDriveType() == JointDriverType.ELEVATOR) * { * Debug.Log("got to 1"); * ElevatorScript es = unitySubNode.unityObject.GetComponent<ElevatorScript>(); * if(unitySubNode.GetSkeletalJoint().cDriver.portA == i + 1) * { * Debug.Log("got to 2"); * es.currentTorque = pwm[i]*.00706155183333f * Init.PHYSICS_MASS_MULTIPLIER; * } * }*/ } } }
// 以下、メイン処理.リジッドボディと絡めるので、FixedUpdate内で処理を行う. void FixedUpdate() { float h = Input.GetAxis("Horizontal"); // 入力デバイスの水平軸をhで定義 float v = Input.GetAxis("Vertical"); // 入力デバイスの垂直軸をvで定義 anim.SetFloat("Speed", v); // Animator側で設定している"Speed"パラメタにvを渡す anim.SetFloat("Direction", h); // Animator側で設定している"Direction"パラメタにhを渡す anim.speed = animSpeed; // Animatorのモーション再生速度に animSpeedを設定する currentBaseState = anim.GetCurrentAnimatorStateInfo(0); // 参照用のステート変数にBase Layer (0)の現在のステートを設定する rb.useGravity = true; //ジャンプ中に重力を切るので、それ以外は重力の影響を受けるようにする // 以下、キャラクターの移動処理 velocity = new Vector3(0, 0, v); // 上下のキー入力からZ軸方向の移動量を取得 // キャラクターのローカル空間での方向に変換 velocity = transform.TransformDirection(velocity); //以下のvの閾値は、Mecanim側のトランジションと一緒に調整する if (v > 0.1) { velocity *= forwardSpeed; for (int i = 0; i < CarMotars.Length - 1; i++) { JointMotor jointMotor = CarMotars[i].motor; jointMotor.targetVelocity = 1000; jointMotor.force = 1000; CarMotars[i].motor = jointMotor; } } else if (v < -0.1) { for (int i = 0; i < CarMotars.Length - 1; i++) { JointMotor jointMotor = CarMotars[i].motor; jointMotor.targetVelocity = -1000; jointMotor.force = 1000; CarMotars[i].motor = jointMotor; } } if (Input.GetButtonDown("Jump")) // スペースキーを入力したら //アニメーションのステートがLocomotionの最中のみジャンプできる { if (currentBaseState.nameHash == locoState) { //ステート遷移中でなかったらジャンプできる if (!anim.IsInTransition(0)) { rb.AddForce(Vector3.up * jumpPower, ForceMode.VelocityChange); anim.enabled = false; // Animatorにジャンプに切り替えるフラグを送る } } } // 上下のキー入力でキャラクターを移動させる transform.localPosition += velocity * Time.fixedDeltaTime; // 以下、Animatorの各ステート中での処理 // Locomotion中 // 現在のベースレイヤーがlocoStateの時 if (currentBaseState.nameHash == locoState) { //カーブでコライダ調整をしている時は、念のためにリセットする if (useCurves) { resetCollider(); } } // JUMP中の処理 // 現在のベースレイヤーがjumpStateの時 else if (currentBaseState.nameHash == jumpState) { cameraObject.SendMessage("setCameraPositionJumpView"); // ジャンプ中のカメラに変更 // ステートがトランジション中でない場合 if (!anim.IsInTransition(0)) { // 以下、カーブ調整をする場合の処理 if (useCurves) { // 以下JUMP00アニメーションについているカーブJumpHeightとGravityControl // JumpHeight:JUMP00でのジャンプの高さ(0〜1) // GravityControl:1⇒ジャンプ中(重力無効)、0⇒重力有効 float jumpHeight = anim.GetFloat("JumpHeight"); float gravityControl = anim.GetFloat("GravityControl"); if (gravityControl > 0) { rb.useGravity = false; //ジャンプ中の重力の影響を切る } // レイキャストをキャラクターのセンターから落とす Ray ray = new Ray(transform.position + Vector3.up, -Vector3.up); RaycastHit hitInfo = new RaycastHit(); // 高さが useCurvesHeight 以上ある時のみ、コライダーの高さと中心をJUMP00アニメーションについているカーブで調整する if (Physics.Raycast(ray, out hitInfo)) { if (hitInfo.distance > useCurvesHeight) { col.height = orgColHight - jumpHeight; // 調整されたコライダーの高さ float adjCenterY = orgVectColCenter.y + jumpHeight; col.center = new Vector3(0, adjCenterY, 0); // 調整されたコライダーのセンター } else { // 閾値よりも低い時には初期値に戻す(念のため) resetCollider(); } } } // Jump bool値をリセットする(ループしないようにする) anim.SetBool("Jump", false); } } // IDLE中の処理 // 現在のベースレイヤーがidleStateの時 else if (currentBaseState.nameHash == idleState) { //カーブでコライダ調整をしている時は、念のためにリセットする if (useCurves) { resetCollider(); } // スペースキーを入力したらRest状態になる if (Input.GetButtonDown("Jump")) { anim.SetBool("Rest", true); } } // REST中の処理 // 現在のベースレイヤーがrestStateの時 else if (currentBaseState.nameHash == restState) { //cameraObject.SendMessage("setCameraPositionFrontView"); // カメラを正面に切り替える // ステートが遷移中でない場合、Rest bool値をリセットする(ループしないようにする) if (!anim.IsInTransition(0)) { anim.SetBool("Rest", false); } } }
void Start() { hj = GetComponent <HingeJoint>(); motor = new JointMotor(); }
// Update is called once per frame void Update() { object controlState = null; if (!IsRunningOnMono) { controlState = GamePad.GetState(PlayerIndex.One); } // Forward and backwards movement foreach (WheelMotor motor in motors) { HingeJoint hinge = motor.motor.GetComponent <HingeJoint>(); JointMotor thisMotor = hinge.motor; if (IsRunningOnMono || !((GamePadState)controlState).IsConnected) { thisMotor.targetVelocity = motorSpeed * Input.GetAxis("Horizontal"); } else { thisMotor.targetVelocity = motorSpeed * (((GamePadState)controlState).Triggers.Right + -((GamePadState)controlState).Triggers.Left); } hinge.motor = thisMotor; } // Steering control foreach (ControlArm controlArm in controlArms) { HingeJoint hinge = controlArm.controlArm.GetComponent <HingeJoint>(); JointSpring spring = hinge.spring; if (IsRunningOnMono || !((GamePadState)controlState).IsConnected) { spring.targetPosition = steeringAngle * Input.GetAxis("Horizontal"); } else { spring.targetPosition = steeringAngle * ((GamePadState)controlState).ThumbSticks.Left.X; } // Forklift steering if (controlArm.inverse) { spring.targetPosition = -spring.targetPosition; } hinge.spring = spring; } // Skid compensate foreach (WheelMotor motor in motors) { HingeJoint wheelhinge = motor.motor.GetComponent <HingeJoint>(); JointMotor thisMotor = wheelhinge.motor; if (motor.leftSide && Input.GetAxis("Horizontal") < 0) { thisMotor.targetVelocity = thisMotor.targetVelocity / skidCompensation; } else if (!(motor.leftSide) && Input.GetAxis("Horizontal") > 0) { thisMotor.targetVelocity = thisMotor.targetVelocity * skidCompensation; } wheelhinge.motor = thisMotor; } // Self righting transform.localEulerAngles = new Vector3(0, transform.localEulerAngles.y, transform.localEulerAngles.z); }
// Function to Instantiate a DNA Object into the Unity World public void InstantiateDNAasUnityCreature(Vector3 instantiationPosition) { GameObject CreatureParentObject = new GameObject(CreatureName); CreatureParentObject.GetComponent <Transform>().position = instantiationPosition; startingPosition = instantiationPosition; // This is used to score the robot // Creating the blocks and instantiating them foreach (Block blockObject in arrayOfBlocks) { // instantiation vector is the blockposition within the DNA added to the insantiation position of the DNA itself Vector3 instantiationVector = blockObject.GetBlockPosition() + instantiationPosition; if (blockObject.GetBlockType() != null) { // Set the instantiated block object starting position blockObject.SetInstantiatedObjectStartingLocation(instantiationVector); // Actually instantiate the block GameObject tempSegment = blockObject.InstantiateBlock(instantiationVector); // Find the block's name, and set that name to the name of the segment blockObject.CalculateBlockName(CreatureName); // This stores the value of the unity objects name in the refered to block object inside the DNA tempSegment.name = blockObject.GetBlockName(); // Set the weight of the object tempSegment.GetComponent <Rigidbody>().mass = blockObject.GetBlockWeight(); // Change color tempSegment.GetComponent <Renderer>().material.SetColor("_Color", blockObject.GetBlockColor()); // Parent it ParentChild(CreatureParentObject, tempSegment); if (blockObject.GetBlockStabilized() == true) { Rigidbody stablebody = tempSegment.GetComponent <Rigidbody>(); stablebody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; } } } // Jointing the objects in the world for (int i = 0; i < arrayOfBlocks.GetLength(0); i++) { for (int j = 0; j < arrayOfBlocks.GetLength(1); j++) { for (int k = 0; k < arrayOfBlocks.GetLength(2); k++) { //Fixed X Joint if (arrayOfBlocks[i, j, k].GetPosXCon().GetIsFixedJoint() == true) { int temp = i + 1; string name = CreatureName + "x" + i + "y" + j + "z" + k; string name2 = CreatureName + "x" + temp + "y" + j + "z" + k; GameObject.Find(name).AddComponent <FixedJoint>().connectedBody = GameObject.Find(name2).GetComponent <Rigidbody>(); } else if (arrayOfBlocks[i, j, k].GetPosXCon().GetConType() != null) { // Non-Fixed X Joint string curBlockName = CreatureName + "x" + i + "y" + j + "z" + k; int temp = i + 2; string blockToBeConnectedName = CreatureName + "x" + temp + "y" + j + "z" + k; // instantiate the joint object at the vector below, this is the location of where the next block would be if it existed. Vector3 instantiationVector = arrayOfBlocks[i + 1, j, k].GetBlockPosition() + instantiationPosition; // The connectionobject is the actual joint object, which has a hinge joint on it GameObject xconnectionobject = arrayOfBlocks[i, j, k].GetPosXCon().InstantiateConnection(instantiationVector, Quaternion.Euler(new Vector3(0, 0, 90))); // name the connection object the current blocks name, and the description of the location xconnectionobject.name = curBlockName + "posXCon"; // The hingejoint on the connection object is then retreived and its target is set to the block next to it xconnectionobject.GetComponent <HingeJoint>().connectedBody = GameObject.Find(blockToBeConnectedName).GetComponent <Rigidbody>(); // ANd the current block is given a hinge joint that connects to the connection object, this is where the str/speed is applied HingeJoint xPosHJ = GameObject.Find(curBlockName).AddComponent <HingeJoint>(); xPosHJ.axis = arrayOfBlocks[i, j, k].GetPosXCon().GetConAxis(); xPosHJ.connectedBody = xconnectionobject.GetComponent <Rigidbody>(); JointMotor xPosMotor = xPosHJ.motor; xPosMotor.force = arrayOfBlocks[i, j, k].GetPosXCon().GetConStr(); xPosMotor.targetVelocity = arrayOfBlocks[i, j, k].GetPosXCon().GetConSpeed(); xPosHJ.motor = xPosMotor; xPosHJ.useMotor = true; ParentChild(CreatureParentObject, xconnectionobject); // This is for the rendering of the joint visualization: if (RenderJointObjects) { GameObject RenderTemp = MonoBehaviour.Instantiate(JointRenderingObject, instantiationVector, Quaternion.Euler(new Vector3(0, 0, 90))); RenderTemp.name = CreatureName + " + " + curBlockName + " + " + blockToBeConnectedName; RenderTemp.GetComponent <JointRendering>().baseObject = GameObject.Find(curBlockName); RenderTemp.GetComponent <JointRendering>().targetObject = GameObject.Find(blockToBeConnectedName); ParentChild(CreatureParentObject, RenderTemp); } } // Fixed Y Joint if (arrayOfBlocks[i, j, k].GetPosYCon().GetIsFixedJoint() == true) { int temp = j + 1; string name = CreatureName + "x" + i + "y" + j + "z" + k; string name2 = CreatureName + "x" + i + "y" + temp + "z" + k; GameObject.Find(name).AddComponent <FixedJoint>().connectedBody = GameObject.Find(name2).GetComponent <Rigidbody>(); } else if (arrayOfBlocks[i, j, k].GetPosYCon().GetConType() != null) { string curBlockName = CreatureName + "x" + i + "y" + j + "z" + k; int temp = j + 2; string blockToBeConnectedName = CreatureName + "x" + i + "y" + temp + "z" + k; // instantiate the joint object at the vector below, this is the location of where the next block would be if it existed. Vector3 instantiationVector = arrayOfBlocks[i, j + 1, k].GetBlockPosition() + instantiationPosition; // The connectionobject is the actual joint object, which has a hinge joint on it GameObject yconnectionobject = arrayOfBlocks[i, j, k].GetPosYCon().InstantiateConnection(instantiationVector, Quaternion.Euler(new Vector3(0, 0, 0))); // name the connection object the current blocks name, and the description of the location yconnectionobject.name = curBlockName + "posYCon"; // The hingejoint on the connection object is then retreived and its target is set to the block next to it yconnectionobject.GetComponent <HingeJoint>().connectedBody = GameObject.Find(blockToBeConnectedName).GetComponent <Rigidbody>(); // ANd the current block is given a hinge joint that connects to the connection object, this is where the str/speed is applied HingeJoint yPosHJ = GameObject.Find(curBlockName).AddComponent <HingeJoint>(); yPosHJ.axis = arrayOfBlocks[i, j, k].GetPosYCon().GetConAxis(); yPosHJ.connectedBody = yconnectionobject.GetComponent <Rigidbody>(); JointMotor yPosMotor = yPosHJ.motor; yPosMotor.force = arrayOfBlocks[i, j, k].GetPosYCon().GetConStr(); yPosMotor.targetVelocity = arrayOfBlocks[i, j, k].GetPosYCon().GetConSpeed(); yPosHJ.motor = yPosMotor; yPosHJ.useMotor = true; ParentChild(CreatureParentObject, yconnectionobject); if (RenderJointObjects) { GameObject RenderTemp = MonoBehaviour.Instantiate(JointRenderingObject, instantiationVector, Quaternion.Euler(new Vector3(0, 0, 90))); RenderTemp.name = CreatureName + " + " + curBlockName + " + " + blockToBeConnectedName; RenderTemp.GetComponent <JointRendering>().baseObject = GameObject.Find(curBlockName); RenderTemp.GetComponent <JointRendering>().targetObject = GameObject.Find(blockToBeConnectedName); ParentChild(CreatureParentObject, RenderTemp); } } //Fixed Z Joint if (arrayOfBlocks[i, j, k].GetPosZCon().GetIsFixedJoint() == true) { int temp = k + 1; string name = CreatureName + "x" + i + "y" + j + "z" + k; string name2 = CreatureName + "x" + i + "y" + j + "z" + temp; GameObject.Find(name).AddComponent <FixedJoint>().connectedBody = GameObject.Find(name2).GetComponent <Rigidbody>(); } else if (arrayOfBlocks[i, j, k].GetPosZCon().GetConType() != null) { // Non-Fixed X Joint string curBlockName = CreatureName + "x" + i + "y" + j + "z" + k; int temp = k + 2; string blockToBeConnectedName = CreatureName + "x" + i + "y" + j + "z" + temp; // instantiate the joint object at the vector below, this is the location of where the next block would be if it existed. Vector3 instantiationVector = arrayOfBlocks[i, j, k + 1].GetBlockPosition() + instantiationPosition; // The connectionobject is the actual joint object, which has a hinge joint on it GameObject zconnectionobject = arrayOfBlocks[i, j, k].GetPosZCon().InstantiateConnection(instantiationVector, Quaternion.Euler(new Vector3(90, 0, 0))); // name the connection object the current blocks name, and the description of the location zconnectionobject.name = curBlockName + "posZCon"; // The hingejoint on the connection object is then retreived and its target is set to the block next to it zconnectionobject.GetComponent <HingeJoint>().connectedBody = GameObject.Find(blockToBeConnectedName).GetComponent <Rigidbody>(); // And the current block is given a hinge joint that connects to the connection object, this is where the str/speed is applied HingeJoint zPosHJ = GameObject.Find(curBlockName).AddComponent <HingeJoint>(); zPosHJ.axis = arrayOfBlocks[i, j, k].GetPosZCon().GetConAxis(); zPosHJ.connectedBody = zconnectionobject.GetComponent <Rigidbody>(); JointMotor zPosMotor = zPosHJ.motor; zPosMotor.force = arrayOfBlocks[i, j, k].GetPosZCon().GetConStr(); zPosMotor.targetVelocity = arrayOfBlocks[i, j, k].GetPosZCon().GetConSpeed(); zPosHJ.motor = zPosMotor; zPosHJ.useMotor = true; ParentChild(CreatureParentObject, zconnectionobject); if (RenderJointObjects) { GameObject RenderTemp = MonoBehaviour.Instantiate(JointRenderingObject, instantiationVector, Quaternion.Euler(new Vector3(0, 0, 90))); RenderTemp.name = CreatureName + " + " + curBlockName + " + " + blockToBeConnectedName; RenderTemp.GetComponent <JointRendering>().baseObject = GameObject.Find(curBlockName); RenderTemp.GetComponent <JointRendering>().targetObject = GameObject.Find(blockToBeConnectedName); ParentChild(CreatureParentObject, RenderTemp); } } } } } }
public void writeKeyVal(string key, JointMotor val) { writeKey(key); writeRawValue(val); }
void Update() { if (!dead) { if (Input.GetKeyDown(KeyCode.E)) { Ray ray = new Ray(camera.transform.position, (hand.transform.position - camera.transform.position).normalized); RaycastHit hit; if (Physics.Raycast(ray, out hit, reachingDistance)) { GameObject obj = hit.collider.gameObject; if (obj.tag == "Door" && animator.GetBool("LookThruJudas") == false) { if (animator.GetBool("OpenDoor") == false && animator.GetCurrentAnimatorStateInfo(0).IsName("Idle")) { animator.SetBool("OpenDoor", true); } else if (animator.GetBool("OpenDoor") == true && animator.GetCurrentAnimatorStateInfo(0).IsName("PorteOuverte")) { animator.SetBool("OpenDoor", false); } } else if (obj.tag == "Judas" && animator.GetBool("OpenDoor") == false) { if (animator.GetBool("LookThruJudas") == false && animator.GetCurrentAnimatorStateInfo(0).IsName("Idle")) { animator.SetBool("LookThruJudas", true); } else if (animator.GetBool("LookThruJudas") == true && animator.GetCurrentAnimatorStateInfo(0).IsName("JudasOuvert")) { animator.SetBool("LookThruJudas", false); } } else if (obj.tag == "MovingObject" && obj.name == "Bowl") { Bowl bowl = obj.GetComponent <Bowl> (); if (!bowl.isFull) { bowl.isFull = true; dogFoodCan.SetActive(false); } } } } if (Input.GetMouseButtonDown(0) && !holdObject) { Ray ray = new Ray(camera.transform.position, (hand.transform.position - camera.transform.position).normalized); RaycastHit hit; if (Physics.Raycast(ray, out hit, reachingDistance)) { if (hit.collider.tag == "MovingObject") { holdObject = hit.collider.gameObject; HingeJoint ho = holdObject.AddComponent <HingeJoint> () as HingeJoint; JointMotor motor = ho.motor; ho.useMotor = true; motor.freeSpin = true; ho.anchor = Vector3.forward * 0.75f; ho.axis = Vector3.forward; ho.connectedBody = hand.GetComponent <Rigidbody> (); } } } else if (Input.GetMouseButtonUp(0) && holdObject) { Destroy(holdObject.GetComponent <HingeJoint> ()); holdObject = null; } } }