Du bist nicht angemeldet.

Stilllegung des Forums
Das Forum wurde am 05.06.2023 nach über 20 Jahren stillgelegt (weitere Informationen und ein kleiner Rückblick).
Registrierungen, Anmeldungen und Postings sind nicht mehr möglich. Öffentliche Inhalte sind weiterhin zugänglich.
Das Team von spieleprogrammierer.de bedankt sich bei der Community für die vielen schönen Jahre.
Wenn du eine deutschsprachige Spieleentwickler-Community suchst, schau doch mal im Discord und auf ZFX vorbei!

Werbeanzeige

Martin Mundorf

Treue Seele

  • »Martin Mundorf« ist der Autor dieses Themas

Beiträge: 262

Wohnort: Waldorf, Kr. Ahrweiler

Beruf: Althistoriker

  • Private Nachricht senden

1

10.11.2017, 17:11

Meine Ideen rund um die KI

Hallo zusammen..


meine KI findet nicht alle Wegpunkte. WEeiß der Kuckuck, wo der Fehler liegt.. habe jetzt schon Stunden damit zugebracht, und die Lösung immer noch nicht gefunden...

Der Code soll eiegntlich bewirken, das bei jedem Wegpunkt der Index (-> gehe zum nächsten) raufgesetzt wird, und wenn er bei array.length -1 ist, auch wieder auf 0 gesetzt wird.
Der Debug.break fischt mir auch eine "2" heraus, aber trotzdem wandert "Klaus" nur zwischen Element 0 und 1 hin und her ?(

Ich raff´ es einfach nicht ...kann mir da jemand die Erleuchtung bringen?



C#-Quelltext

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
                            if (!setDestination) 
                            {
                            
                                navmesh.SetDestination (patrolSettings.waypoints [patrolSettings .currWayPt].transform.position);
                                setDestination = true;
                            }

                            if ((navmesh.remainingDistance <= navmesh.stoppingDistance) || reachedDestinantion && navmesh .pathPending )
                            {
                                setDestination = false;
                
                                walkingToDest = false;
                                forward = LerpSpeed (forward, 0, 15);
                                currentWaitTime -= Time.deltaTime;
                
                                if (patrolSettings.waypoints [patrolSettings .currWayPt].lookAtTarget != null)
                                    currentLookTransform = patrolSettings.waypoints [patrolSettings .currWayPt].lookAtTarget;


                                if (currentWaitTime <= 0) 
                                {
                                    patrolSettings .currWayPt  = (patrolSettings .currWayPt + 1) % patrolSettings.waypoints.Length ;
                                    reachedDestinantion = false;


//                                  if (patrolSettings.currWayPt == patrolSettings.waypoints.Length-1)
//                                  Debug.Break ();
                                    
                                        
                                } 
                                else 
                                {
                                    reachedDestinantion = true;


                                }
                
                            } 
                            else 
                            {
                                LookAtPosition (navmesh.steeringTarget);
                                walkingToDest = true;
                                forward = LerpSpeed (forward, 0.5f, 15);
                                currentWaitTime = patrolSettings.waypoints [waypointIndex].Verweildauer;
                                currentLookTransform = null;
                            }
»Martin Mundorf« hat folgendes Bild angehängt:
  • probll.png
"Eine Signatur ist das Buchstaben-Zahlen-Zettelchen unten an ein einem Buch in der Bibliothek!"



was ich zur Zeit ausprobiere: 3rd person Shooter <- hierfür suche ich noch Unterstützung.


"Lehrjahre": Im Lande der Hasen
mein ewiges Spielprojekt "Straights & Rows".
meine Grafiken "ohne Verwendungszweck"

Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von »Martin Mundorf« (03.02.2018, 10:57) aus folgendem Grund: Um den Thread beizubehalten, aber um das Thema zu erweitern


Martin Mundorf

Treue Seele

  • »Martin Mundorf« ist der Autor dieses Themas

Beiträge: 262

Wohnort: Waldorf, Kr. Ahrweiler

Beruf: Althistoriker

  • Private Nachricht senden

2

11.11.2017, 17:30

Problem gelöst

ich hab nur was am Code umgestellt...und jetzt funktioniert es... richtig verstanden hab ichs nicht... aber es funzt :golly:


C#-Quelltext

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
    if ((navmesh.remainingDistance <= navmesh.stoppingDistance) || reachedDestinantion && navmesh .pathPending )
                            {
                                    if (currentWaitTime <= 0) 
                                    {
                    patrolSettings.currWayPt = (patrolSettings.currWayPt + 1) % patrolSettings.waypoints.Length ;
                                        reachedDestinantion = false;

                                    } 
                                    else 
                                        {
                                    reachedDestinantion = true;
                                    }



                                    setDestination = false;
                
                                walkingToDest = false;
                                forward = LerpSpeed (forward, 0, 15);
                                currentWaitTime -= Time.deltaTime;
                
                if (patrolSettings.waypoints [patrolSettings.currWayPt].lookAtTarget != null)
                    currentLookTransform = patrolSettings.waypoints [patrolSettings.currWayPt].lookAtTarget;
                            
                                
                
                            } 
                            else 
                            {
                                LookAtPosition (navmesh.steeringTarget);
                                walkingToDest = true;
                                forward = LerpSpeed (forward, 0.5f, 15);
                                currentWaitTime = patrolSettings.waypoints [waypointIndex].Verweildauer;
                                currentLookTransform = null;
                            }
"Eine Signatur ist das Buchstaben-Zahlen-Zettelchen unten an ein einem Buch in der Bibliothek!"



was ich zur Zeit ausprobiere: 3rd person Shooter <- hierfür suche ich noch Unterstützung.


"Lehrjahre": Im Lande der Hasen
mein ewiges Spielprojekt "Straights & Rows".
meine Grafiken "ohne Verwendungszweck"

Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von »Martin Mundorf« (11.11.2017, 18:41)


David Scherfgen

Administrator

Beiträge: 10 382

Wohnort: Hildesheim

Beruf: Wissenschaftlicher Mitarbeiter

  • Private Nachricht senden

3

11.11.2017, 18:53

Ist das eigentlich wirklich die Formatierung deines Codes, was du hier zeigst?
Bei dem Chaos kann man ja nicht durchblicken ;)

Martin Mundorf

Treue Seele

  • »Martin Mundorf« ist der Autor dieses Themas

Beiträge: 262

Wohnort: Waldorf, Kr. Ahrweiler

Beruf: Althistoriker

  • Private Nachricht senden

4

11.11.2017, 19:40

ja also..äh ...jetzt sieht der Code wieder etwas zivilisierter aus :rolleyes: :D

Nachdem diese Nuß geknackt ist, tut meine KI was sie soll: sie sucht sich selbständig Waypoints zum patroullieren, verweilt an den Wegpunkten - und meldet sich selbständig beim GameController an - und bei Tod auch wieder ab (allerdings bekomm ich dann noch eine object missing Fehlermeldung, die aber zZ nicht weiter schlimm ist - und in ein anderes Themenfeld gehört.

Vielleicht poste ich meinen KI-Code später noch im Projekt-Thread :)
"Eine Signatur ist das Buchstaben-Zahlen-Zettelchen unten an ein einem Buch in der Bibliothek!"



was ich zur Zeit ausprobiere: 3rd person Shooter <- hierfür suche ich noch Unterstützung.


"Lehrjahre": Im Lande der Hasen
mein ewiges Spielprojekt "Straights & Rows".
meine Grafiken "ohne Verwendungszweck"

Martin Mundorf

Treue Seele

  • »Martin Mundorf« ist der Autor dieses Themas

Beiträge: 262

Wohnort: Waldorf, Kr. Ahrweiler

Beruf: Althistoriker

  • Private Nachricht senden

5

11.11.2017, 21:26

Nachtrag: es funktioniert immer noch nicht. Beim Durchlaufen der Wegpunkte kam nach einer zeit ein zu hoher Indexwert raus - den fang ich jetzt provisorisch mit try/catch ab - das Ergebnis ist: es werden wieder Wegpunkte übersprungen :crazy: :fie: :dash:

Herrschaften, halten Sie sich fest: Es folgt: mein AI-Code. Der Casus Knacktus liegt zwischen Zeile 389 und Zeile 489.

C#-Quelltext

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
using UnityEngine;
using System.Collections;
using System.Collections.Generic ;

[RequireComponent(typeof(CharacterMovement))]
[RequireComponent(typeof(CharacterStats))]
[RequireComponent(typeof(Animator))]
public class AI : MonoBehaviour {

    //public UnityEngine.AI.NavMeshAgent navmesh;
    private CharacterMovement characterMove { get { return GetComponent<CharacterMovement> (); } set { characterMove = value; } }
    public  Animator animator { get { return GetComponent<Animator> (); } set { animator = value; } }
    public CharacterStats characterStats { get { return GetComponent<CharacterStats> (); } set { characterStats = value; } }
    //
    private WeaponHandler weaponHandler {get{return GetComponent <WeaponHandler > ();}set { weaponHandler = value; }}
    //
    private UnityEngine.AI.NavMeshAgent navmesh {get{return GetComponentInChildren<UnityEngine.AI.NavMeshAgent>(); } set { navmesh = value;}}


    [System.Serializable ]
    public class States
    {
    public enum AIState { Patrol, Attack, Guard, WalkTo, Follow }
    public AIState aiState;
    }
    public States states;

    [System.Serializable]
    public class TeamSettings
    {
        public string Fraktion;
        public Transform Kapitän;
        public bool follow_in_team = false;

    }
    public TeamSettings teamS;

    [System.Serializable]   
    public class PatrolSettings
    {
        [Header ("Auto-Set-Wegpunkt Prefab")]
        public KI_Wegpunkt dynamic_WP;

        [Header ("aktuelle Wegpunkte")]
        public KI_Wegpunkt [] waypoints;
        public int currWayPt = 0;

        [Header("Wegpunktfindung")]
        public KI_Wegpunkt  NZZ;
    //  public List < KI_Wegpunkt  > meine_WPKTE = new List <KI_Wegpunkt  >();

    }
    public PatrolSettings patrolSettings;


    // Sichtfeld
    [System.Serializable]
    public class SightSettings
    {
        public LayerMask sightLayers;
        public float sightRange = 30f;
        public float fieldOfView = 90f;
        public float eyeheight;
    }
    public SightSettings sight;

    // Angriff
    [System .Serializable ]
    public class AttackSettings
    {
        public float fireChance = 0.1f;
        public float MindestAbstand = 3.0f;
        public float MaximalAbstand;
        public bool OutOfAmmo = false;
    }
    public AttackSettings attack;
    //

    // Waypoint-Gedönse
    private float currentWaitTime;
    private int waypointIndex;
    private Transform currentLookTransform;
    private bool walkingToDest;

    //Navigations-Gedönse
    private bool setDestination;
    private bool reachedDestinantion;
    private bool aiming;

    // variables Ziel
    [HideInInspector]
    public  Vector3  income;
    //

    // Bewegung
    private float forward;

    //Zielerfassung im Kampf
    public Transform target;
    private Vector3 targetLastKnownPosition;
    private CharacterStats[] allCharacters;

    private GameObject GC;


    //Stati
    [HideInInspector]
    public string currentState; 
    [HideInInspector]
    public string oldState;

    public bool unbewaffnet = false;

    void Awakening()
    {
        GC = GameObject.FindGameObjectWithTag ("GameController");
        GameController ggc = GC.GetComponent <GameController  > ();

        switch (characterStats.egS.team) 
        {
        case CharacterStats.Eigenschaften.Team.Friend:
            ggc.teamSP.Freunde.Add (this.gameObject);
            if (teamS.Kapitän == null) {
                teamS.Kapitän = GameObject.FindGameObjectWithTag ("Player").transform ;
            }
            break;
        case CharacterStats.Eigenschaften.Team.Enemy :
            ggc.teamSP.Feinde.Add (this.gameObject);
            break;
        case CharacterStats.Eigenschaften.Team.Neutral  :
            ggc.teamSP.Neutrale .Add (this.gameObject);
            break;
        case CharacterStats.Eigenschaften.Team.Spectator   :
            ggc.teamSP.Beobachter.Add (this.gameObject);
            break;

        }

    }


    // Use this for initialization
    void Start () 
    {

        Awakening ();
        attack.MaximalAbstand = sight.sightRange;

        nav_Setup ();

        // team Setup
        if (teamS.Kapitän != null) 
        {
            income = teamS.Kapitän.transform.position;
        }

        // Wegpunkte Setup
        GetAllWaypoints ();
        ClosestWaypoint ();


    }

    void nav_Setup()
    {
        if (navmesh == null) {
            Debug.LogError ("We need a navmesh to traverse the world with.");
            enabled = false;
            return;
        }

        if (navmesh.transform == this.transform) {
            Debug.LogError ("The navmesh agent should be a child of the character: " + gameObject.name);
            enabled = false;
            return;
        }

        navmesh.speed = 0;
        navmesh.acceleration = 0;
        navmesh.autoBraking = false;

        if (navmesh.stoppingDistance == 0) 
        {
            //navmesh.stoppingDistance = 1.3f;
            navmesh .stoppingDistance = attack .MindestAbstand / 2;
        }

        reachedDestinantion = false;
    }

    public void startsetzen()
    {
        KI_Wegpunkt actwp = Instantiate (patrolSettings .dynamic_WP , this.transform.position, Quaternion.identity) as KI_Wegpunkt ;
        //actwp.transform.parent = null;

        actwp.is_Master = true;

    }

    public  void GetAllCharacters () 
    {
        allCharacters = GameObject.FindObjectsOfType<CharacterStats> ();
    }
    



    // Update is called once per frame
    void Update () 
    {
        currentState = states .aiState.ToString ();

        if (forward >= 0.8f)
        {
            animator.SetBool ("isRunning", true);
        } 
        else
        {
            animator.SetBool ("isRunning", false);
        }
        //TODO: Animate the strafe when the enemy is trying to shoot us.
        characterMove.Animate (forward, 0);
        navmesh.transform.position = transform.position;

        if (weaponHandler != null) 
        {
            
            weaponHandler.Aim (aiming); 
        }



        if (target = this.transform )
            target = null;
        
        GetAllCharacters ();
        LookForTarget ();

        patrolSettings.NZZ = ClosestWaypoint ();

        if (ClosestWaypoint ().is_Master) 
        {
            patrolSettings .waypoints = ClosestWaypoint ().mein_Gatter.ToArray () ;
        }


        switch (states.aiState ) 
        {
        case AI.States.AIState.Patrol:
                teamS.follow_in_team = false;
                Patrol ();
                break;
        case AI.States.AIState.Attack:
                FireAtEnemy ();
                break;
        case  AI.States.AIState.Guard:
            teamS.follow_in_team = false;
                GuardAtPoint ();
                break;
        case  AI.States.AIState.Follow:
                teamS.follow_in_team = true;
                follow (teamS.Kapitän.position);
                break;
        case  AI.States.AIState.WalkTo:
            LookAtPosition (income);
            proceed (income);
            break;

            }

    }

    // langsam auf ein Ziel zuwenden
    public  void LookAtPosition (Vector3 pos) 
    {


        Quaternion didiRotation;
        Vector3 relliPos;
        Vector3 tippi;
        Vector3 tripper;

        tippi = pos;
        tripper = this.transform.position;
        tippi.y = 0;
        tripper.y = 0;
        relliPos = tippi - tripper;

        didiRotation = Quaternion.LookRotation (relliPos);
        transform .rotation = Quaternion .Slerp (this.transform .rotation , didiRotation , characterMove .movement .turnSpeed  * Time.deltaTime );

    }



    public void LookForTarget () 
    {
        if (allCharacters.Length > 0) {
            foreach (CharacterStats c in allCharacters) {
                //if (c != this.characterStats && c.egS.Fraktion != this.characterStats.egS.Fraktion && c == ClosestEnemy() )
                if (c != this.characterStats && c.egS.team  != this.characterStats.egS.team  && c == ClosestEnemy() )
                {
                    RaycastHit hit;
                    Vector3 start = transform.position + (transform.up * sight.eyeheight);
                    Vector3 dir = c.gameObject.GetComponent <CharacterMovement >().other_Setup .Kopf .transform.position  - start;
                    float sightAngle = Vector3.Angle (dir, transform.forward);
                    if (Physics.Raycast (start, dir, out hit, sight.sightRange, sight.sightLayers) &&
                        sightAngle < sight.fieldOfView && hit.collider.GetComponent<CharacterStats>() && hit.transform != this.transform ) {
                        target = hit.transform;
                        targetLastKnownPosition = Vector3.zero;
                    }
                    else
                    {
                        if (target != null) {
                            targetLastKnownPosition = target.position;
                            target = null;
                        }
                    }
                }
            }
        }
    }

    CharacterStats ClosestEnemy ()
    {
        CharacterStats closestCharacter = null;
        float minDistance = Mathf.Infinity;
        foreach (CharacterStats c in allCharacters) {
        //  if (c != characterStats && c.egS.Fraktion != characterStats.egS.Fraktion && c.egS.Fraktion != 3 && characterStats.egS.Fraktion != 3) {
            if (c != characterStats && c.egS.team != characterStats.egS.team  && c.egS.team != (CharacterStats.Eigenschaften .Team .Neutral  ) && characterStats.egS.team != (CharacterStats.Eigenschaften .Team .Neutral )) {
                float distToCharacter = Vector3.Distance (c.transform.position, transform.position);
                if (distToCharacter < minDistance) {
                    closestCharacter = c;
                    minDistance = distToCharacter;
                
                }
            }
        }
        return closestCharacter;
    }

    // den nächstgelegenen Wegpunkt suchen
    private KI_Wegpunkt[] allWaypoints;

    public  void GetAllWaypoints () 
    {
        allWaypoints  = GameObject.FindObjectsOfType<KI_Wegpunkt > ();
    }
    // nächsten Master-Waypoint finden
    KI_Wegpunkt ClosestWaypoint ()
    {
        KI_Wegpunkt  closestWaypoint = null;
        float minDistance = Mathf.Infinity;
        foreach (KI_Wegpunkt c in allWaypoints) 
        {
            if (c.is_Master )
            {
            float distToCharacter = Vector3.Distance (c.transform.position, this.transform.position);
                if (distToCharacter < minDistance) 
                {
                    closestWaypoint = c;
                    minDistance = distToCharacter;
                }
            }

        }
        return closestWaypoint;
    }

    // nächsten Waypoint finden
    int cloWay()
    {
        if (patrolSettings.waypoints.Length == 0) return -1;
        int closest = 0;
        float lastDist = Vector3.Distance (this.transform.position, patrolSettings.waypoints [0].transform.position);
        for (int i = 1; i < patrolSettings.waypoints.Length; i++) 
        {
            float thisDist = Vector3.Distance (this.transform.position, patrolSettings.waypoints [i].transform.position);
            if (lastDist > thisDist && i != patrolSettings.currWayPt) 
            {
                closest = 1;
            }
        }
        return closest;

    }

    // Patroullie gehen
    void Patrol () 
    {

        oldState = currentState;
        if (target == null || attack .OutOfAmmo ) 
        {
            aiming = false;

        
//          Vector3 direction = patrolSettings.waypoints [patrolSettings.currWayPt].transform.position - this.transform.position;
//          this.transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (direction), 5 * Time.deltaTime);
//
//
//
//          forward = LerpSpeed (forward, 0.5f, 15);
//          if (direction.magnitude < navmesh.stoppingDistance) 
//
//          {
//          //  Debug.Log ("waypoint erreicht");
//
//              patrolSettings.currWayPt += 1;
//
//              if (patrolSettings.currWayPt > patrolSettings.waypoints.Length-1)
//                  patrolSettings.currWayPt = 0;
//              
//          }
            // ########################################################//


            if (!setDestination) 
            {
                try 
                {       
                    navmesh.SetDestination (patrolSettings.waypoints [patrolSettings.currWayPt].transform.position);
                }
                catch (System.IndexOutOfRangeException ex) 
                {
                    navmesh.SetDestination (patrolSettings.waypoints [0].transform.position);
                }


                setDestination = true;
            }                           
            if ((navmesh.remainingDistance <= navmesh.stoppingDistance) || reachedDestinantion && navmesh .pathPending )
            {
                if (currentWaitTime <= 0) 
                {
                    patrolSettings.currWayPt = (patrolSettings.currWayPt + 1) % patrolSettings.waypoints.Length;
                    reachedDestinantion = false;
                } 
                else 
                {
                    reachedDestinantion = true;
                }

                setDestination = false;
                walkingToDest = false;
                forward = LerpSpeed (forward, 0, 15);
                currentWaitTime -= Time.deltaTime;

                try
                {
                if (patrolSettings.waypoints [patrolSettings.currWayPt].lookAtTarget != null)
                    currentLookTransform = patrolSettings.waypoints [patrolSettings.currWayPt].lookAtTarget;
                }
                catch (System.IndexOutOfRangeException ex) 
                {
                    if (patrolSettings.waypoints [0].lookAtTarget != null)
                        currentLookTransform = patrolSettings.waypoints [0].lookAtTarget;
                }

                            
            } 
            else 
            {

                LookAtPosition (navmesh.steeringTarget);
                walkingToDest = true;
                forward = LerpSpeed (forward, 0.5f, 15);
                try
                {
                currentWaitTime = patrolSettings.waypoints [waypointIndex].Verweildauer;
                }
                catch (System.IndexOutOfRangeException ex) 
                {
                    currentWaitTime = patrolSettings.waypoints [0].Verweildauer;
                }
                currentLookTransform = null;
            }
//                      
///////////////////////////////////////###############################                      
        } 
        else 
        {
            // Hier müsste wohl auch In Deckung Gehen hinkommen...
            states.aiState =  AI.States.AIState.Attack;
        }
    }

    // auf Gegner feuern
public  void FireAtEnemy()
    {

        /// nur auf KI des anderen Team und nicht auf Neutrale oder Tote schießen
        //if (target != null && !attack.OutOfAmmo && target.GetComponent<CharacterStats > ().egS.Fraktion != characterStats.egS.Fraktion && target.GetComponent<CharacterStats > ().egS.Fraktion != 3 && target.GetComponent<CharacterStats > ().egS.health > 0) {
            
        if (target != null && !attack.OutOfAmmo && 
            target.GetComponent<CharacterStats > ().egS.team != characterStats.egS.team && 
            (target.GetComponent<CharacterStats > ().egS .team != CharacterStats.Eigenschaften.Team.Neutral) &&
                target.GetComponent<CharacterStats > ().egS.health > 0) 
        {
            AttackBehaviour ();
            LookAtPosition (target.position);
            Vector3 start = transform.position + transform.up;
            Vector3 dir = target.position - transform.position;
            Ray ray = new Ray (start, dir);


            /// auf das Ziel zukommen
            float diss = Vector3.Distance (target.position, transform.position);
            float vorwärts;
            if (diss >= attack.MindestAbstand * 2) 
            {
                vorwärts = 1.0f;
            } 
            else 
            {
                vorwärts = 0.0f;
            }
            characterMove.Animate (vorwärts, 0.0f);

            float vall = GetComponent <CharacterStats > ().egS.shooting; 
            attack.fireChance = vall;
            float Chance = Random.Range (0.0f, 10.0f);

            if (Chance <= attack.fireChance)
                weaponHandler.FireCurrentWeapon (ray);

        } 

        /// falls Ziel tot, nicht vorhanden, oder eigener CHarakter entdeckt wurde
        else if (target == null || target == this.transform) 
        {
            aiming = false;
            AI.States .AIState ss = (AI.States .AIState)System.Enum.Parse (typeof(AI.States .AIState), oldState);
            if (ss == AI.States.AIState.Follow) {
                states.aiState = ss;
            } else if (ss == AI.States.AIState.Patrol) {
                states.aiState = ss;
            } else if (ss == AI.States.AIState.Guard) {
                states.aiState = ss;
            } else if (ss == AI.States.AIState.WalkTo) {
                states.aiState = ss;
            }
        }



    }

    //Angriff
    void AttackBehaviour()
    {
        if (weaponHandler.currentWeapon.ammo.carryingAmmo == 0 && weaponHandler.currentWeapon.ammo.clipAmmo == 0) 
        {
            attack.OutOfAmmo = true;
        
            Debug.Log ("no more ammo");
            states.aiState =  AI.States.AIState.Guard ;
            return;
        }


        aiming = true;
        walkingToDest = false;
        setDestination = false;
        reachedDestinantion = false;
        currentLookTransform = null; 
        forward = LerpSpeed (forward ,0,15);
    }



    // Dem Team-Anführer folgen
    public void follow(Vector3 income)
    {
        oldState = currentState;
        teamS.follow_in_team = true;

        if (income == null) 
        {
            states.aiState =  AI.States.AIState.Guard ;
        }
            
        FireAtEnemy ();

        if (!setDestination) 
        {
            navmesh.SetDestination (income);
            setDestination = true;
        }
        if ((navmesh.remainingDistance <= navmesh.stoppingDistance) || reachedDestinantion && navmesh.pathPending )
        {
            setDestination = false;
            LookAtPosition (teamS.Kapitän.transform.position);
            GuardAtPoint ();

        } 
        else 
        {
            
            LookAtPosition (navmesh.steeringTarget);
            LookAtPosition (teamS.Kapitän.transform.position);
            walkingToDest = true;
            if (navmesh.remainingDistance < attack .MindestAbstand ) 
            {
                forward = 0.5f;
            } 
            else 
            {
                forward = 1.0f;
            }

            currentWaitTime = Random.Range (3, 4); 
            currentLookTransform = null;
        

        }
    }


    // zu einer bestimmten Position im Terrain gehen
    public void proceed(Vector3 income)
    {
        oldState = currentState;

        navmesh.SetDestination (income);
        setDestination = true;

        if ((navmesh.remainingDistance <= navmesh.stoppingDistance) || reachedDestinantion && navmesh.pathPending )
        {
            setDestination = false;
            LookAtPosition (income);
            GuardAtPoint ();

        } 
        else 
        {

            LookAtPosition (navmesh.steeringTarget);
            LookAtPosition (income);
            walkingToDest = true;
            if (navmesh.remainingDistance < attack .MindestAbstand ) 
            {
                forward = 0.5f;
            } 
            else 
            {
                forward = 1.0f;
            }

            currentWaitTime = Random.Range (3, 4); 
            currentLookTransform = null;


        }
    }

    // an einer Stelle stehen bleiben
    void GuardAtPoint()
    {
        oldState = currentState;
        reachedDestinantion = true;
        setDestination = false;
        walkingToDest = false;
        //animator.Play ("idle_1"); 
        animator.SetBool ("isRunning",false); 
        characterMove.Animate (0.0f  , 0.0f);
        target = null;
        //LookForTarget ();
        // teamS.follow_in_team = false;


    }



    //public    IEnumerator backToPatrol() 
    //  {
    //      yield return new WaitForSeconds (0.2f);
    //      states.aiState =  AI.States.AIState.Patrol;
    //  }
    //
    //public    IEnumerator backToFollow() 
    //  {
    //      yield return new WaitForSeconds (0.2f);
    //      states.aiState =  AI.States.AIState.Follow ;
    //  }
    //
    //
    //  public  IEnumerator backToGuard() 
    //  {
    //      yield return new WaitForSeconds (0.2f);
    //      states.aiState =  AI.States.AIState.Guard ;
    //  }

    // irgendwas aus dem original-tutorial mit dem Animator
    void OnAnimatorIK () 
    {

        animator.SetIKPosition (AvatarIKGoal.LeftHand, weaponHandler.currentWeapon.userSettings.leftHandIKTarget.position);
        if (currentLookTransform != null && !walkingToDest) {
            animator.SetLookAtPosition (currentLookTransform.position);
            animator.SetLookAtWeight (1, 0, 0.5f, 0.7f);
        } 
        else if (target != null) 
        {
            float dist = Vector3.Distance (target.position, transform.position);
            if (dist > 3) {
                animator.SetLookAtPosition (target.transform.position + transform.right * 0.3f);
                animator.SetLookAtWeight (1, 1, 0.3f, 0.2f);
            } 
            else 
            {
                // FixME to do a smoother transition; 
                //  Vector3 newlookPos = Vector3.Lerp (target.transform .position + transform.right, target.transform.position + target.up  + transform.right, Time.deltaTime * 5 );
                animator.SetLookAtPosition (target.transform.position + target.up  + transform.right * 0.3f);
                animator.SetLookAtWeight (1, 1, 0.3f, 0.2f);
            }


        }
    }

    float LerpSpeed (float curSpeed, float destSpeed, float time) 
    {
        curSpeed = Mathf.Lerp (curSpeed, destSpeed, Time.deltaTime * time);
        return curSpeed;
    }

//  void Patrol () 
//  {
//
//
//      oldState = currentState;
//
//      if (target == null || attack .OutOfAmmo ) 
//      {
//
//          //  Patrolbehaviour ();
//          aiming = false;
//          //
//          if (!navmesh.isOnNavMesh) {
//              Debug.Log (this.name + " We're off the navmesh");
//              return;
//          }
//
//          if (patrolSettings.waypoints.Length  == 0) {
//              return;
//          }
//
//
//          if (!setDestination) 
//          {
//              ///
//              //navmesh.SetDestination (patrolSettings.waypoints [waypointIndex].destination.position);
//              ///
//              navmesh.SetDestination (patrolSettings.waypoints [waypointIndex].transform.position);
//              setDestination = true;
//          }
//          if ((navmesh.remainingDistance <= navmesh.stoppingDistance) || reachedDestinantion && navmesh .pathPending )
//          {
//              setDestination = false;
//
//              walkingToDest = false;
//              forward = LerpSpeed (forward, 0, 15);
//              currentWaitTime -= Time.deltaTime;
//
//              if (patrolSettings.waypoints [waypointIndex].lookAtTarget != null)
//                  currentLookTransform = patrolSettings.waypoints [waypointIndex].lookAtTarget;
//              if (currentWaitTime <= 0) {
//                  waypointIndex = (waypointIndex + 1) % patrolSettings.waypoints.Length ;
//                  reachedDestinantion = false;
//              } 
//              else 
//              {
//                  reachedDestinantion = true;
//              }
//
//          } 
//          else 
//          {
//              LookAtPosition (navmesh.steeringTarget);
//              walkingToDest = true;
//              forward = LerpSpeed (forward, 0.5f, 15);
//              //currentWaitTime = patrolSettings.waypoints [waypointIndex].waitTime;
//
//              ///
//              //currentWaitTime = Random.Range (patrolSettings.waypoints [waypointIndex].minWaitTime, patrolSettings.waypoints [waypointIndex].maxWaitTime); 
//              ///
//              currentWaitTime = Random.Range (patrolSettings.waypoints [waypointIndex].min_Verweilzeit , patrolSettings.waypoints [waypointIndex].max_Verweilzeit ); 
//
//              currentLookTransform = null;
//          }
//          //
//      } 
//      else 
//      {
//          // Hier müsste wohl auch In Deckung Gehen hinkommen...
//          states.aiState =  AI.States.AIState.Attack;
//      }
//  }
}

//  [System.Serializable]
//  public class WaypointBase 
//  {
//      public Transform destination;
//
//      public Transform lookAtTarget;
//      public float minWaitTime = 1.0f;
//      public float maxWaitTime = 6.0f;
//  //  public float waitTime;
//
//  }
//      public WaypointBase waypointBASE;
//
//  [System.Serializable]   
//  public class PatrolSettings
//  {
//      public WaypointBase[] waypoints;
//
//  }
//  public PatrolSettings patrolSettings;

//  [System.Serializable]
//  public class WaypointBase 
//  {
//      public Transform destination;
//
//      public Transform lookAtTarget;
//      public float minWaitTime = 1.0f;
//      public float maxWaitTime = 6.0f;
//      //  public float waitTime;
//
//  }
//  public WaypointBase waypointBASE;
"Eine Signatur ist das Buchstaben-Zahlen-Zettelchen unten an ein einem Buch in der Bibliothek!"



was ich zur Zeit ausprobiere: 3rd person Shooter <- hierfür suche ich noch Unterstützung.


"Lehrjahre": Im Lande der Hasen
mein ewiges Spielprojekt "Straights & Rows".
meine Grafiken "ohne Verwendungszweck"

TGGC

1x Rätselkönig

Beiträge: 1 799

Beruf: Software Entwickler

  • Private Nachricht senden

6

11.11.2017, 22:27

Aehhh, ja.

Ich glaub da sind noch Bugs drin.

Martin Mundorf

Treue Seele

  • »Martin Mundorf« ist der Autor dieses Themas

Beiträge: 262

Wohnort: Waldorf, Kr. Ahrweiler

Beruf: Althistoriker

  • Private Nachricht senden

7

11.11.2017, 23:10

dieser Analyse stimme ich vollumpfänglich zu...
allerdings wäre ich auch dankbar für Hinweise zu Ent-Käferung... :hmm:
"Eine Signatur ist das Buchstaben-Zahlen-Zettelchen unten an ein einem Buch in der Bibliothek!"



was ich zur Zeit ausprobiere: 3rd person Shooter <- hierfür suche ich noch Unterstützung.


"Lehrjahre": Im Lande der Hasen
mein ewiges Spielprojekt "Straights & Rows".
meine Grafiken "ohne Verwendungszweck"

8

13.11.2017, 08:56

Moin,

das ist aber ganz schön viel Code. Vorneweg, der Fehler ist wohl eher nicht für einen Außenstehenden zu finden.

zu erst mal OT. du solltest dich für eine Sprache entscheiden. Da C# auf Englisch aufbaut sollte es natürlich Englisch sein. Das Mischmasch macht es echt schwer zu lesen. (siehe den kopierten Ausschnitt)

C#-Quelltext

1
2
3
4
5
6
7
8
[System .Serializable ]
public class AttackSettings
{
     public float fireChance = 0.1f;
     public float MindestAbstand = 3.0f;
     public float MaximalAbstand;
     public bool OutOfAmmo = false;
}


Zu meinem Tip. Du solltest deinen Code mal ein wenig überarbeiten. Warum zum Beispiel speicherst du die abzulaufenden Wegpunkte in der KI? (zumindest dem Namen nach). Die Wegpunkte solltest du separat verwalten und der KI einzeln vorwerfen, damit sie zu diesem hin läuft.

Macht diese Zeile wirklich das, was du möchtest?

C#-Quelltext

1
patrolSettings.currWayPt = (patrolSettings.currWayPt + 1) % patrolSettings.waypoints.Length;
(Zeile 436)

Grüße

David Scherfgen

Administrator

Beiträge: 10 382

Wohnort: Hildesheim

Beruf: Wissenschaftlicher Mitarbeiter

  • Private Nachricht senden

9

13.11.2017, 10:35

Du solltest dich auch mal für eine Schreibweise von Variablen und Methoden entscheiden. Manchmal fängst du mit Kleinbuchstaben an, manchmal mit Großbuchstaben.

Martin Mundorf

Treue Seele

  • »Martin Mundorf« ist der Autor dieses Themas

Beiträge: 262

Wohnort: Waldorf, Kr. Ahrweiler

Beruf: Althistoriker

  • Private Nachricht senden

10

13.11.2017, 11:53

Also...das mit der Sprache ist so ne Sache... in meinem Kopf ist deutsch logischer und kommt schneller an, wenn ich mich auf etwas konzentrieren soll; klar leuchtet mir eine durchgehende stringente Sprache ein, aber für die Funktionalität ists es ja unerheblich, ob der float jetzt min_distance oder min_Distanz heißt. (Außerdem hilft mir das im Code zu unterscheiden, was ich ggf aus einem tutorial habe, und was von mir selbst ist. Kann also u.U. nützlich bei der Fehlersuche sein ;) )

@David hab deinen Post gerade gesehen: ja, die Groß/klein Schreibweise ist natürlich fürs Auge besser, das stimmt :whistling: sry

Warum die Wegpunkte in der KI abgespeichert sind?
Nun - weil sie diejenige ist, die diese ja auch ablaufen muß :)
nein, im Ernst:
Das Prinzip habe ich aus dem tutorial, an das ichmich anfangs gehalten habe.
Allerdings habe ich das nun so modifiziert, daß die KI zu Spielbeginn sich ihre Wegpunkte selber sucht, damit ich sie nicht bei jedem KI-Bot manuell setzen muß. Dadurch ist es mir auch möglich in der Laufzeit neue Bots zu spawnen.
Das prinzip sieht folgendermaßen aus: auf dem ganzen Terrain des Levels sind Gruppen von Wegpunkten gelegt. Ein Wegpunkt dieser Gruppe ist ein Master-Wegpunkt, der eine Liste der ihn umgebenden Wegpunkte erstellt (innerhalb eines Radius).
Die KI macht das ähnlich: sie sucht bei Spielbeginn nach dem nächstgelegenen Master-Wegpunkt, und übernimmt dess Liste dann als ihre eigenen Wegpunkte.
Da dies auch im Update erfolgt, kann eine KI nzu beginn in Wegpunktgruppe A laufen, durch Kampfhandlungen o.ä. aber näher an einen anderen Masterwegpunkt B geraten, und (sofern der Status "Patrol" ist), dann dort patroullieren.

zu der zeile 436:
Die habe ich in mehreren tutorials zur iteration so gesehen, und verwendet. Ich selbst hab auch mit int i ++; experimentiert, allerdings ohne Erfolg.
Ich habe aber eines festgestellt: Wenn die Insgesamt-Anzahl der Bots im Spiel relativ gering ist:

macht die zeile das was sie soll! also das Problem scheint irgendwo zu liegen, wo ich derzeit noch nciht durchschaue. Im Moment geht es (wieder).

:search: :hmm: :hmm:

WENN ich irgendwo in der Beschreibung gerade oder in dem Code einen kapitalen Bock geschossen habe, sagt es mir bitte, und zeigt mir nen Lösungsweg auf, ich möcht ja was lernen.
(und das kann ich zB durch logisches nachvollziehen, das nicht zu abstrakt ist - u.a. auch deswegen manchmal "deutscher" Code) ^^
"Eine Signatur ist das Buchstaben-Zahlen-Zettelchen unten an ein einem Buch in der Bibliothek!"



was ich zur Zeit ausprobiere: 3rd person Shooter <- hierfür suche ich noch Unterstützung.


"Lehrjahre": Im Lande der Hasen
mein ewiges Spielprojekt "Straights & Rows".
meine Grafiken "ohne Verwendungszweck"

Werbeanzeige