勇哥注:
需求:弄一个输入信号,它在true或者false切换时,产生随机摆放的物料。
同时演示一下输出调试信息的办法。
代码比较简单,没什么好解释的。
C#代码:
using NXOpen; using NXOpen.CAE; using System; public class UserBehavior : BehaviorDef { RigidBody m_RigidBody = null; SourceBehavior m_Source = null; MCDSignal m_Signal = null; ListingWindow listingWindow; Random r = new Random(); // 定义刚体的位置与方向变量 NXOpen.VectorArithmetic.Vector3 oldPosition; NXOpen.VectorArithmetic.Matrix3 oldOrientation; NXOpen.VectorArithmetic.Vector3 newPosition; NXOpen.VectorArithmetic.Matrix3 newOrientation; NXOpen.Session theSession; NXOpen.Part workPart; bool bFlag = false; bool lastSignalValue = false; // 用于存储上一次的信号值 public override void Define(IDefinitionContext access) { access.Connect("Rigid Body", out m_RigidBody); access.Connect("Object Source", out m_Source); access.Connect("Trigger1", out m_Signal); m_Source.Active = false; } public override void Start(IRuntimeContext context) { oldPosition = m_RigidBody.Position; oldOrientation = m_RigidBody.Orientation; theSession = NXOpen.Session.GetSession(); workPart = theSession.Parts.Work; // open listingWindow listingWindow = theSession.ListingWindow; if (!listingWindow.IsOpen) listingWindow.Open(); } public override void Stop(IRuntimeContext context) { // Insert stopping code here } public override void Step(IRuntimeContext context, double dt) { // NXOPEN api不能在Step函数中调用,因为Step在工作线程中运行。 //只有MCD运行时api可以在Step函数中调用 //在这里插入仿真步骤代码 if (m_Signal != null) { if (m_Signal.BoolValue != lastSignalValue) { // 先输出调试信息,再更新lastSignalValue listingWindow.WriteLine($"Signal changed to1: {m_Signal.BoolValue}, Last signal was: {lastSignalValue}"); lastSignalValue = m_Signal.BoolValue; // 更新上一次的信号值 m_Source.Active = true; //listingWindow.WriteLine($"{DateTime.Now.ToString()}....."); listingWindow.WriteLine($"m_Source.Active is set to: {m_Source.Active}"); listingWindow.WriteLine("Inside if (m_Source.Active) block"); listingWindow.WriteLine($"{DateTime.Now.ToString()}....."); // 重新初始化Random对象以确保更好的随机性 r = new Random(); // 设置随机位置x newPosition = oldPosition; newPosition.x += (double)r.Next(-150, 150) / 1000; // 重置方向 newOrientation = oldOrientation; // Z轴以任意角度旋转 newOrientation.Rotate(0.0, 0.0, 1.0, Math.PI * 180 / (double)r.Next(1, 30)); // 设置刚体的新位置 m_RigidBody.Position = newPosition; // 为刚体设置新的方向 m_RigidBody.Orientation = newOrientation; } } } public override void Refresh(IRuntimeContext context) { // Insert simulation refreshing code here. This is called when it is safe // to read and change runtime variables outside of the main control loop. } public override void Repaint() { // Insert simulation repainting code here. This is where you use the data // taken from the runtime to update the display. } } public override void Repaint() { // Insert simulation repainting code here. This is where you use the data // taken from the runtime to update the display. } }
本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:

本帖最后由 勇哥,很想停止 于 2025-07-31 19:05:52 编辑 
